fimo 2.4.0-staging.2 → 2.4.0-staging.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/assets/skills/fimo-cli/SKILL.md +1 -1
  2. package/assets/skills/fimo-cli/references/branches.md +4 -4
  3. package/assets/skills/fimo-cli/references/deploy.md +2 -5
  4. package/assets/skills/fimo-cli/references/domains.md +5 -5
  5. package/assets/skills/fimo-cli/references/hosting.md +5 -4
  6. package/assets/skills/fimo-cli/references/preview.md +1 -1
  7. package/assets/skills/fimo-cli/references/projects.md +5 -5
  8. package/assets/skills/fimo-code/SKILL.md +1 -0
  9. package/assets/skills/fimo-code/references/assets.md +4 -2
  10. package/assets/skills/fimo-code/references/best-practices/next.md +0 -2
  11. package/assets/skills/fimo-code/references/content/schema.md +4 -1
  12. package/assets/skills/fimo-code/references/design.md +2 -2
  13. package/assets/skills/fimo-code/references/frameworks/astro.md +37 -1
  14. package/assets/skills/fimo-code/references/frameworks/compatibility.md +5 -5
  15. package/assets/skills/fimo-code/references/frameworks/hosting.md +23 -2
  16. package/assets/skills/fimo-code/references/frameworks/seo-head.md +78 -0
  17. package/assets/skills/fimo-code/references/frameworks/sveltekit.md +57 -4
  18. package/assets/skills/fimo-migration/SKILL.md +4 -0
  19. package/assets/skills/fimo-migration/references/qa.md +6 -0
  20. package/assets/skills/fimo-studio/references/billing-and-credits.md +7 -4
  21. package/assets/skills/fimo-studio/references/seo-settings.md +2 -0
  22. package/dist/cli/bundle.json +1 -1
  23. package/dist/cli/index.js +11 -10
  24. package/dist/runtime/seo/head.d.ts +31 -0
  25. package/dist/runtime/seo/head.js +47 -0
  26. package/dist/runtime/seo/index.d.ts +1 -0
  27. package/dist/runtime/seo/index.js +1 -0
  28. package/dist/runtime/seo/resolver.d.ts +16 -2
  29. package/dist/scripts/sync-schemas.js +12 -5
  30. package/package.json +8 -8
  31. package/templates/astro/.fimo/config.json +1 -0
  32. package/templates/astro/AGENTS.md +1 -1
  33. package/templates/astro/astro.config.mjs +1 -0
  34. package/templates/astro/package.json +2 -2
  35. package/templates/astro/src/layouts/Base.astro +20 -4
  36. package/templates/astro/src/pages/[locale]/index.astro +1 -1
  37. package/templates/astro/src/pages/[locale]/projects/[slug].astro +4 -1
  38. package/templates/astro/src/pages/index.astro +1 -1
  39. package/templates/astro/src/pages/projects/[slug].astro +4 -1
  40. package/templates/nextjs/package.json +3 -3
  41. package/templates/react-router/package.json +4 -4
  42. package/templates/sveltekit/AGENTS.md +1 -1
  43. package/templates/sveltekit/package.json +2 -2
  44. package/templates/sveltekit/src/routes/+layout.server.ts +4 -0
  45. package/templates/sveltekit/src/routes/+layout.svelte +12 -0
  46. package/templates/sveltekit/src/routes/[[locale=locale]]/+page.svelte +0 -5
  47. package/templates/vite/package.json +4 -4
package/dist/cli/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __fimoCreateRequire } from 'node:module';
3
3
  const require = __fimoCreateRequire(import.meta.url);
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)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string=""+input,index=string.indexOf(close,open2.length);return~index?open2+replaceClose(string,close,replace,index)+close:open2+string+close},"formatter"),replaceClose=__name((string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);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
- `)}__name(emit,"emit");function okEnvelope(event){let base={status:"ok",command:event.command,schema_version:1};switch(event.kind){case"message":{let data={headline:event.headline};return event.details&&(data.details=event.details),base.data=data,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}),data={...event.jsonData,columns:event.columns.map(c2=>c2.key),rows};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"kv":{let data={fields:event.fields};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"script":return base.data={shell:event.shell,script:event.script},base;case"raw":{let field=event.field??"value";return base.data={[field]:event.value},base}case"result":return base.data=event.data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}}return __name(okEnvelope,"okEnvelope"),{ok(event){emit(stdout,okEnvelope(event))},error(event){emit(stderr,{status:"error",command:event.command,schema_version:1,error:{code:event.code,message:event.message,...event.details?{details:event.details}:{},...event.hint?{hint:event.hint}:{}}})},warn(event){emit(stdout,{status:"ok",command:event.command,schema_version:1,warnings:[event.message]})},info(event){let env={status:"ok",command:event.command,schema_version:1,data:{...event.jsonData,message:event.message}};event.hint&&(env.hint=event.hint),emit(stdout,env)}}}var init_renderer_json=__esm({"../../packages/cli-kit/dist/renderer-json.js"(){"use strict";__name(makeJsonRenderer,"makeJsonRenderer")}});function stripAnsi(input){return input.replace(OSC_PATTERN,"").replace(CSI_PATTERN,"")}function displayWidth(input){return stripAnsi(input).length}function padToWidth(input,target){let visible=displayWidth(input);return visible>=target?input:input+" ".repeat(target-visible)}var CSI_PATTERN,OSC_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";CSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/g,OSC_PATTERN=/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g;__name(stripAnsi,"stripAnsi");__name(displayWidth,"displayWidth");__name(padToWidth,"padToWidth")}});function makePrettyRenderer(opts){let{palette:palette2,symbols,context,stdout,stderr}=opts;function write(stream,line){stream.write(`${line}
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)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string=""+input,index=string.indexOf(close,open2.length);return~index?open2+replaceClose(string,close,replace,index)+close:open2+string+close},"formatter"),replaceClose=__name((string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);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,pendingWarnings=[];function emit(stream,envelope){let warnings=[...pendingWarnings,...envelope.warnings??[]].filter((warning,index,all)=>all.indexOf(warning)===index);pendingWarnings=[],stream.write(`${JSON.stringify(warnings.length>0?{...envelope,warnings}:envelope)}
5
+ `)}__name(emit,"emit");function okEnvelope(event){let base={status:"ok",command:event.command,schema_version:1};switch(event.kind){case"message":{let data={headline:event.headline};return event.details&&(data.details=event.details),base.data=data,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}),data={...event.jsonData,columns:event.columns.map(c2=>c2.key),rows};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"kv":{let data={fields:event.fields};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"script":return base.data={shell:event.shell,script:event.script},base;case"raw":{let field=event.field??"value";return base.data={[field]:event.value},base}case"result":return base.data=event.data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}}return __name(okEnvelope,"okEnvelope"),{ok(event){emit(stdout,okEnvelope(event))},error(event){emit(stderr,{status:"error",command:event.command,schema_version:1,error:{code:event.code,message:event.message,...event.details?{details:event.details}:{},...event.hint?{hint:event.hint}:{}}})},warn(event){pendingWarnings.push(event.message)},info(event){let env={status:"ok",command:event.command,schema_version:1,data:{...event.jsonData,message:event.message}};event.hint&&(env.hint=event.hint),emit(stdout,env)}}}var init_renderer_json=__esm({"../../packages/cli-kit/dist/renderer-json.js"(){"use strict";__name(makeJsonRenderer,"makeJsonRenderer")}});function stripAnsi(input){return input.replace(OSC_PATTERN,"").replace(CSI_PATTERN,"")}function displayWidth(input){return stripAnsi(input).length}function padToWidth(input,target){let visible=displayWidth(input);return visible>=target?input:input+" ".repeat(target-visible)}var CSI_PATTERN,OSC_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";CSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/g,OSC_PATTERN=/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g;__name(stripAnsi,"stripAnsi");__name(displayWidth,"displayWidth");__name(padToWidth,"padToWidth")}});function makePrettyRenderer(opts){let{palette:palette2,symbols,context,stdout,stderr}=opts;function write(stream,line){stream.write(`${line}
6
6
  `)}__name(write,"write");function renderMessage(event){if(write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),event.details&&renderAlignedFields(event.details," "),event.warnings)for(let w3 of event.warnings)write(stdout,` ${palette2.warn(symbols.warn)} ${w3}`);maybeHint(event.hint)}__name(renderMessage,"renderMessage");function renderAlignedFields(fields,indent){let keys=Object.keys(fields),longest=keys.reduce((m,k)=>Math.max(m,k.length),0);for(let k of keys){let value=fields[k];value!=null&&write(stdout,`${indent}${palette2.dim(`${k}:`.padEnd(longest+2))}${formatScalar(value)}`)}}__name(renderAlignedFields,"renderAlignedFields");function renderTable2(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`);let{columns,rows}=event;if(rows.length===0){write(stdout,palette2.dim(" (no rows)")),maybeHint(event.hint);return}let widths=columns.map(c2=>Math.max(displayWidth(c2.label),...rows.map(r=>displayWidth(String(r[c2.key]??""))))),header=columns.map((c2,i)=>padToWidth(c2.label,widths[i])).join(" ");write(stdout,` ${palette2.dim(header)}`);for(let row2 of rows){let active=event.isActive?.(row2)===!0,cells=columns.map((c2,i)=>{let raw=String(row2[c2.key]??""),padded=padToWidth(raw,widths[i]),role=event.cellStyle?.(row2,c2.key);return role?paintCell(padded,role):active?palette2.accent(padded):padded}),marker=active?palette2.success(symbols.active):" ";write(stdout,`${marker} ${cells.join(" ")}`)}maybeHint(event.hint)}__name(renderTable2,"renderTable");function paintCell(cell,role){switch(role){case"success":return palette2.success(cell);case"warn":return palette2.warn(cell);case"error":return palette2.error(cell);case"dim":return palette2.dim(cell);case"accent":return palette2.accent(cell)}}__name(paintCell,"paintCell");function renderKv(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),renderAlignedFields(event.fields,""),maybeHint(event.hint)}__name(renderKv,"renderKv");function renderScript(event){stdout.write(event.script.endsWith(`
7
7
  `)?event.script:`${event.script}
8
8
  `)}__name(renderScript,"renderScript");function renderRaw(event){stdout.write(`${event.value}
@@ -196,14 +196,15 @@ ${block.code}
196
196
 
197
197
  `)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&&sections.push(...document.details.map(reportBlockMarkdown)),sections.join(`
198
198
 
199
- `)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z46.enum(REPORT_TONES),blockCommon={title:z46.string().trim().min(1).max(120).optional(),fallback:z46.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z46.object({type:z46.literal("text"),...blockCommon,text:z46.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z46.object({type:z46.literal("metric"),...blockCommon,items:z46.array(z46.object({value:z46.string().trim().min(1).max(24),unit:z46.string().trim().min(1).max(12).optional(),label:z46.string().trim().min(1).max(160),note:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z46.array(z46.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z46.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z46.object({type:z46.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z46.string().trim().min(1).max(12).optional(),points:z46.array(z46.object({label:z46.string().trim().min(1).max(24),value:z46.number().finite(),highlight:z46.boolean().optional()}).strict()).min(2).max(24),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z46.object({type:z46.literal("list"),...blockCommon,items:z46.array(z46.object({tone:ReportToneSchema.optional(),label:z46.string().trim().min(1).max(24).optional(),heading:z46.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z46.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z46.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z46.object({type:z46.literal("table"),...blockCommon,columns:z46.array(z46.object({label:z46.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z46.array(z46.object({cells:z46.array(z46.object({text:z46.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z46.object({type:z46.literal("media"),...blockCommon,assetId:z46.uuid(),alt:z46.string().trim().min(1).max(300),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z46.object({type:z46.literal("links"),...blockCommon,items:z46.array(z46.object({label:z46.string().trim().min(1).max(120),url:z46.url({protocol:/^https$/}).max(2e3),description:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z46.object({type:z46.literal("code"),...blockCommon,language:z46.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z46.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z46.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z46.object({title:z46.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z46.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z46.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z46.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(normalizeReportDocument,"normalizeReportDocument");__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z47}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z47.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z47.object({dev:z47.string().trim().min(1).optional(),build:z47.string().trim().min(1).optional(),install:z47.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z47.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z47.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z47.object({type:z47.enum(["header","cookie","query","host"]),key:z47.string().min(1).optional(),value:z47.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z47.array(FimoHostingConditionSchema).min(1).optional(),missing:z47.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),permanent:z47.boolean().optional(),statusCode:z47.union([z47.literal(301),z47.literal(302),z47.literal(307),z47.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z47.object({source:z47.string().min(1),headers:z47.array(z47.object({key:z47.string().min(1),value:z47.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z47.object({rewrites:z47.array(FimoHostingRewriteSchema).optional(),redirects:z47.array(FimoHostingRedirectSchema).optional(),headers:z47.array(FimoHostingHeaderSchema).optional(),cleanUrls:z47.boolean().optional(),trailingSlash:z47.boolean().optional()}).strict(),FimoAppConfigSchema=z47.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path51){return[...path51.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path51){return pageRouteParamNames(path51).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z48}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common2();init_env();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-6-astra","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z48.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z48.string(),displayName:z48.string().nullable(),subdomain:z48.string().nullable().optional(),subdomainUpdatedAt:z48.date().nullable().optional(),organizationId:z48.string().nullable(),createdBy:z48.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z48.boolean().default(!0),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z48.string(),thumbnailUrl:z48.string().nullable(),publishedThumbnailUrl:z48.string().nullable(),category:z48.string().nullable(),snapshotUrl:z48.string().startsWith("/").optional(),appUrl:z48.string().nullable(),lastPublishedAt:z48.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z48.object({name:z48.string().optional(),previewEnabled:z48.boolean().optional(),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z48.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z48.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z48.object({id:z48.uuid(),name:z48.string(),displayName:z48.string().nullable(),thumbnailUrl:z48.string().nullable(),category:z48.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z48.object({id:z48.string(),name:z48.string(),avatar:z48.string().nullable(),color:z48.object({bg:z48.string(),text:z48.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z48.object({path:z48.string(),content:z48.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z48.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z48.object({id:z48.string(),messageId:z48.string(),versionId:z48.string().nullable(),role:ProjectChatMessageRole,parts:z48.array(z48.any()),createdAt:z48.coerce.date()}),MessageUserMetadataSchema=z48.object({id:z48.string(),name:z48.string().nullable().optional(),image:z48.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z48.number(),metadata:z48.object({user:MessageUserMetadataSchema,changeManifest:z48.array(z48.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z48.object({versionId:z48.uuid(),commitHash:z48.string(),name:z48.string(),description:z48.string().nullable(),kind:z48.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z48.object({versionCount:z48.number().int().nonnegative(),snapshotBytes:z48.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z48.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z48.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z48.object({content:z48.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z48.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z48.object({success:z48.boolean(),message:z48.string().optional(),warning:z48.string().optional(),durationMs:z48.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z48.object({isPublished:z48.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z48.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z48.object({label:z48.string().trim().min(1).max(120).optional(),notes:z48.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z48.object({success:z48.boolean(),message:z48.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z48.boolean(),publicationId:z48.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z49}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common2();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z49.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z49.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z49.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z49.string().nullable(),deletedAt:z49.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z49.object({id:z49.union([z49.literal(PREVIEW_ENVIRONMENT_KEY),z49.uuid()]),name:z49.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z49.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z49.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z49.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z49.object({surface:z49.enum(["code","schemas","content","translations","assets","forms"]),status:z49.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z49.number().int().nonnegative(),conflictCount:z49.number().int().nonnegative()}),BranchDiffResultSchema=z49.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z49.coerce.date(),surfaces:z49.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z50}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z50.object({projectId:z50.uuid(),name:z50.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z50.literal("production"),sourceBranch:BranchSchema,isPublished:z50.boolean(),url:z50.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PREVIEW_ENVIRONMENT_KEY),kind:z50.literal("preview"),matchedBranchCount:z50.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z50.literal("custom"),matchedBranchCount:z50.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z50.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z50.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z50.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z50.object({deletedId:z50.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z51}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z51.object({kind:z51.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z51.object({kind:z51.enum(["variable","secret"]),value:z51.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z51.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z51.object({kind:z51.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),key:z51.string(),kind:z51.literal("secret"),exposure:z51.literal("private"),environment:EnvironmentKeySchema,maskedValue:z51.string().optional(),createdAt:z51.date().transform(value=>value.toISOString()),updatedAt:z51.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z51.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z52}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=z52.object({success:z52.literal(!0),downloadUrl:z52.string(),expiresAt:z52.string(),fileSize:z52.number(),duration:z52.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z52.object({success:z52.literal(!0),projectId:z52.string(),projectName:z52.string(),displayName:z52.string(),projectUrl:z52.string(),duration:z52.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z52.object({contentTypes:z52.number(),entries:z52.number(),assets:z52.number(),translations:z52.number(),forms:z52.number(),codeFiles:z52.number(),assetFiles:z52.number()}),ImportPreviewSurfaceDTOSchema=z52.object({name:z52.string(),included:z52.boolean(),count:z52.number().optional(),note:z52.string().optional()}),ImportPreviewDTOSchema=z52.object({projectName:z52.string(),displayName:z52.string().nullable(),category:z52.string().nullable(),exportedAt:z52.string(),version:z52.string(),envScope:z52.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z52.array(ImportPreviewSurfaceDTOSchema),fileSize:z52.number(),fileName:z52.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z52.object({success:z52.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z53}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=z53.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z53.object({type:z53.literal("manual")}),ScheduleTriggerSchema=z53.object({type:z53.literal("schedule"),cron:z53.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:z53.string().optional()}),WebhookTriggerSchema2=z53.object({type:z53.literal("webhook"),path:z53.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z53.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z54}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=z54.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z54.object({token:z54.string().min(1),risk:CapabilityRiskTierSchema,description:z54.string()}),AgentSubAgentSummarySchema=z54.object({name:z54.string().min(1),grant:z54.enum(["inherit","explicit"]),effectiveCaps:z54.array(z54.string().min(1))}),AgentInstallSummaryDTOSchema=z54.object({agentName:z54.string().min(1),env:z54.string().min(1),declaredCapabilities:z54.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z54.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z54.array(CapabilitySummaryEntrySchema),criticalCapabilities:z54.array(CapabilitySummaryEntrySchema),subAgents:z54.array(AgentSubAgentSummarySchema),declaresDelegate:z54.boolean(),cycle:z54.array(z54.string()).nullable(),missingSubAgents:z54.array(z54.string()),warnings:z54.array(z54.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z55}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z55.object({kind:TriggerKindSchema,summary:z55.string()}),AgentListItemTriggerStateSchema=z55.object({triggerIndex:z55.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z55.boolean(),wired:z55.boolean(),syncError:z55.string().nullable()}),AgentListItemDTOSchema=z55.object({name:z55.string().min(1),description:z55.string().nullable(),goalFirstLine:z55.string().nullable(),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),triggers:z55.array(AgentListItemTriggerSchema),triggerStates:z55.array(AgentListItemTriggerStateSchema),paused:z55.boolean(),nextRunAt:z55.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z55.array(AgentListItemDTOSchema))}});import{z as z56}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z56.object({paused:z56.boolean(),cancelledRuns:z56.number().int().nonnegative(),stopIncomplete:z56.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema)}});import{z as z57}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z57.object({args:z57.unknown().optional(),requestId:z57.string().min(1).max(128).optional()}),DispatchSkippedSchema=z57.object({skipped:z57.enum(["no-manual-trigger","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])}),DispatchAcceptedSchema=z57.object({sessionId:z57.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z57.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z58}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z58.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z58.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z58.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z58.object({verb:SurfaceDeltaVerbSchema,key:z58.string(),detail:z58.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z58.record(z58.string(),z58.unknown()).optional()}),PerSurfaceDeltaSchema=z58.object({surface:SurfaceNameSchema,status:z58.enum(["ok","timed_out","failed","unchanged"]),durationMs:z58.number().int().nonnegative().optional(),changedCount:z58.number().int().nonnegative(),conflictCount:z58.number().int().nonnegative(),items:z58.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z58.boolean().optional(),error:z58.string().optional()}),CrossSurfaceFindingSchema=z58.object({id:z58.string(),kind:z58.string(),description:z58.string(),severity:z58.enum(["warning","error"]),source:z58.object({surface:SurfaceNameSchema,key:z58.string()}),target:z58.object({surface:SurfaceNameSchema,key:z58.string()}),actions:z58.array(z58.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z58.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z58.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),agents:z58.array(z58.object({id:z58.string(),name:z58.string(),status:z58.enum(["active","paused","failed"]),lastRunAt:z58.coerce.date().nullable()})).optional(),crossSurface:z58.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z58.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),crossSurface:z58.array(CrossSurfaceFindingSchema).optional(),fingerprint:z58.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z58.object({path:z58.string(),state:z58.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z58.string(),additions:z58.number().int().nonnegative(),deletions:z58.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z58.object({oid:z58.string().optional(),content:z58.string().optional(),truncated:z58.boolean(),binary:z58.boolean()}),CodeConflictDetailSchema=z58.object({path:z58.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z58.string(),targetTipSha:z58.string(),mergeBaseSha:z58.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z58.object({id:z58.string(),slug:z58.string(),contentType:z58.string(),data:z58.record(z58.string(),z58.unknown()),updatedAt:z58.coerce.date()}),ContentRowDiffSchema=z58.object({collection:z58.string(),rowId:z58.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z58.object({name:z58.string(),label:z58.string(),isSingleton:z58.boolean(),fields:z58.record(z58.string(),z58.unknown())}),SchemaTypeDiffSchema=z58.object({typeName:z58.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z58.object({id:z58.string(),name:z58.string(),type:z58.enum(["file","folder"]),mimeType:z58.string().nullable(),storageKey:z58.string().nullable(),url:z58.string().nullable(),fileSize:z58.number().nullable(),width:z58.number().nullable(),height:z58.number().nullable(),altText:z58.string().nullable(),caption:z58.string().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),AssetDiffSchema=z58.object({assetId:z58.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z58.object({locale:z58.string(),key:z58.string(),parent:z58.string().nullable(),child:z58.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z58.object({formName:z58.string(),label:z58.string().nullable(),schemaFingerprint:z58.string(),fields:z58.record(z58.string(),z58.unknown()),settings:z58.record(z58.string(),z58.unknown()).optional()}),FormSchemaDiffSchema=z58.object({formName:z58.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema2(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z58.enum(CONFLICT_KINDS),ConflictSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),kind:ConflictKindSchema.optional(),description:z58.string(),parentValue:z58.unknown().optional(),childValue:z58.unknown().optional(),conflictingFields:z58.array(z58.string()).optional(),code:z58.object({path:z58.string(),unresolvable:z58.boolean().optional(),reason:z58.string().optional()}).optional()}),FieldPickSchema=z58.object({field:z58.string(),choice:z58.enum(["parent","child","pick","ai-pick"]),pickedValue:z58.unknown().optional(),aiSessionId:z58.string().optional()}),ConflictResolutionSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),choice:z58.enum(["parent","child","pick"]),pickedValue:z58.unknown().optional(),fieldPicks:z58.array(FieldPickSchema).optional()}),MergeResultSchema=z58.object({ok:z58.boolean(),mergeId:z58.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()})),conflicts:z58.array(ConflictSchema).optional(),summary:z58.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z58.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z58.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z58.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z58.boolean().optional()}),ResolvedStrategySchema=z58.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z58.boolean()}),MergeRequestSchema=z58.object({from:BranchSchema,allowDirectMerge:z58.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z58.object({mergeId:z58.string().uuid(),streamUrl:z58.string(),strategy:ResolvedStrategySchema,acceptedAt:z58.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z58.object({mergeId:z58.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z58.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z58.array(ConflictSchema),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedBy:z58.string().nullable(),lastEditedAt:z58.coerce.date().nullable(),initiator:z58.object({userId:z58.string().nullable(),role:z58.string().nullable(),agentName:z58.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z58.object({resolutions:z58.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z58.object({mergeId:z58.string().uuid(),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedAt:z58.coerce.date(),lastEditedBy:z58.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z58.object({mergeId:z58.string().uuid(),resolutions:z58.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z58.object({mergeId:z58.string().uuid()}),PublishReleaseRequestSchema=z58.object({version:z58.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z58.string().max(2e4).optional()}),PublishReleaseResultSchema=z58.object({releaseTag:z58.string(),sha:z58.string(),publishedAt:z58.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z59}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z59.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z59.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z59.strictObject({branch:BranchSchema.optional(),project_agents_only:z59.coerce.boolean().optional(),agent_name:z59.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z59.coerce.date().optional(),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(200).default(25),cursor:z59.coerce.date().optional()}),SessionMetricsSchema=z59.object({cpuMs:z59.number().nonnegative().default(0),netBytes:z59.number().nonnegative().default(0),walltimeMs:z59.number().nonnegative().default(0),llmTokensIn:z59.number().nonnegative().optional(),llmTokensOut:z59.number().nonnegative().optional(),stepCount:z59.number().int().nonnegative().optional(),toolCallCounts:z59.record(z59.string().min(1).max(120),z59.number().int().nonnegative()).optional(),toolCallOutcomes:z59.array(z59.object({toolName:z59.string().min(1).max(120),success:z59.boolean(),code:z59.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z59.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z59.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z59.object({capturedAt:z59.coerce.date(),fingerprint:z59.string().min(1).max(256),counts:z59.object({code:z59.number().int().nonnegative(),content:z59.number().int().nonnegative(),schemas:z59.number().int().nonnegative(),labels:z59.number().int().nonnegative(),assets:z59.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z59.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z59.object({diff:DiffReportSchema,code:z59.array(CodeFileDiffSchema.extend({raw:z59.string().max(24576)})).max(200),schemas:z59.array(SchemaTypeDiffSchema).max(200),content:z59.array(z59.object({key:z59.string().min(1).max(512),collection:z59.string().min(1).max(256),slug:z59.string().max(512).optional(),verb:z59.enum(["added","modified","deleted"]),fields:z59.array(z59.object({name:z59.string().min(1).max(256),before:z59.unknown().optional(),after:z59.unknown().optional()})).max(20)})).max(200),labels:z59.array(z59.object({key:z59.string().min(1).max(512),locale:z59.string().min(1).max(64).optional(),before:z59.unknown().nullable(),after:z59.unknown().nullable()})).max(200),assets:z59.array(z59.object({key:z59.string().min(1).max(512),name:z59.string().min(1).max(512),verb:z59.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z59.strictObject({id:z59.uuid(),projectId:z59.uuid(),branch:BranchSchema,agentName:z59.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z59.unknown().optional(),capabilities:z59.array(z59.string()).optional(),dataSources:z59.array(z59.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z59.string().nullable(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),cancelledAt:z59.coerce.date().nullable(),costUsd:z59.number().nonnegative(),costCeilingUsd:z59.number().nonnegative(),creditsUsed:z59.number().int().nonnegative().nullable(),limitCredits:z59.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),longRunning:z59.boolean(),lastCheckpointId:z59.uuid().nullable(),agentBranchId:z59.uuid().nullable(),parentSessionId:z59.uuid().nullable(),terminalReason:z59.string().nullable(),errorMessage:z59.string().nullable(),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z59.string().nullable(),retainedBranch:BranchSchema.nullable().optional(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z59.object({id:z59.uuid(),sessionId:z59.uuid(),checkpointIdx:z59.number().int().nonnegative(),payloadRef:z59.string(),payloadSizeBytes:z59.number().int().nonnegative(),checksum:z59.string().length(64),createdAt:z59.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z59.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z59.object({session:AgentSessionDTOSchema,checkpoints:z59.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z59.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z59.object({reason:z59.string().min(1).max(120).optional()})}});import{z as z60}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=z60.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z60.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z60.object({id:z60.uuid(),envId:z60.uuid(),sessionId:z60.uuid().nullable(),skillName:z60.string().min(1),classification:AgentBranchClassificationSchema,rationale:z60.string().nullable(),summary:z60.string().nullable(),surfaceDeltas:z60.record(z60.string(),z60.unknown()),createdAt:z60.coerce.date(),decidedAt:z60.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z60.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z60.object({path:z60.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z60.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z60.object({code:z60.literal("merge_conflict"),message:z60.string(),conflicts:z60.record(z60.string(),z60.number().int().nonnegative())})}});import{z as z61}from"zod";function agentQuestionCapabilityDecision(request,answer){let answers=answer?.answer.questions??[],decision={requested:[],approved:[],denied:[]};return request.block.steps.forEach((step,index)=>{if(step.body.type!=="capabilities")return;let answered=answers.find(item=>item.stepId===step.id)??answers[index],selected=new Set(answered?.selectedLabels??[]);for(let item of step.body.items)decision.requested.push(item),(selected.has(item.label)?decision.approved:decision.denied).push(item.token)}),decision}var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z61.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z61.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z61.object({description:z61.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z61.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z61.object({id:z61.uuid(),projectId:z61.uuid(),threadId:z61.uuid(),invocationId:z61.uuid(),agentKey:z61.string().min(1).max(120),anchorEnv:z61.string().min(1).max(64),retainedEnv:z61.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z61.string().min(1).nullable(),continuationInvocationId:z61.uuid().nullable(),askedAt:z61.coerce.date(),expiresAt:z61.coerce.date(),closedAt:z61.coerce.date().nullable()});__name(agentQuestionCapabilityDecision,"agentQuestionCapabilityDecision");AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z61.object({questionId:z61.uuid(),invocationId:z61.uuid(),askedAt:z61.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z61.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z61.object({question:AgentQuestionSchema,continuationInvocationId:z61.uuid(),deduped:z61.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z62}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z62.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z62.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z62.enum(["secret_text"]),IntegrationCredentialUsageSchema=z62.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z62.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z62.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z62.object({mode:IntegrationAuthModeSchema,label:z62.string().min(1),description:z62.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z62.object({id:z62.string().min(1),label:z62.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z62.boolean()}),IntegrationToolDefinitionDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),description:z62.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z62.object({title:z62.string().min(1),description:z62.string().min(1),command:z62.string().min(1).optional()}),IntegrationInfoDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),type:z62.enum(["native","mcp"]).optional(),url:z62.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z62.array(IntegrationAuthModeDTOSchema),credentials:z62.array(IntegrationCredentialDefinitionDTOSchema),tools:z62.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z62.enum(["available","unavailable"]).optional(),connectionCapabilities:z62.object({customIdentityCreation:z62.boolean()}).optional(),recipes:z62.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),installed:z62.boolean(),enabled:z62.boolean(),setupState:z62.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z62.string().nullable(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),connectionStatus:z62.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),installedAt:z62.coerce.date().nullable(),updatedAt:z62.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),enabled:z62.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z62.string(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z62.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z62.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z62.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z62.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z62.object({id:z62.uuid(),organizationId:z62.string().min(1),integrationKey:z62.string().min(1),registrationId:z62.uuid().nullable(),alias:z62.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z62.string().min(1),externalAccountName:z62.string().nullable(),externalBotUserId:z62.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z62.array(z62.string()),connectedAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z62.boolean(),isDefault:z62.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z62.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z62.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z62.record(McpHeaderNameSchema,z62.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z62.object({alias:z62.string().min(1).max(120).optional(),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z62.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z62.object({displayName:z62.string().trim().min(1).max(35),backgroundColor:z62.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z62.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),alias:z62.string().min(1).max(120),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}),z62.object({mode:z62.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z62.boolean().optional(),registrationId:z62.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z62.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z62.union([z62.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z62.object({type:z62.literal("mcp"),name:z62.string().trim().min(1).max(120),url:z62.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z62.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z62.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z62.object({integrationKey:z62.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z62.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("oauth"),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),ReusableMcpServerAuthKindSchema=z62.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z62.object({id:z62.uuid(),name:z62.string().min(1),host:z62.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z62.string().min(1),availability:z62.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z62.object({query:z62.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z62.object({serverId:z62.uuid()}),LinearOAuthApplicationDistributionSchema=z62.enum(["private","public"]),OrganizationLinearAppDTOSchema=z62.object({id:z62.uuid(),displayName:z62.string().min(1),description:z62.string().nullable(),iconUrl:z62.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z62.enum(["active","revoked"]),connectionIds:z62.array(z62.uuid()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z62.object({appName:z62.string().trim().min(2).max(80),description:z62.string().trim().max(1e3).optional(),iconUrl:z62.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z62.object({projectId:z62.uuid(),registrationId:z62.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z62.object({integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),integrationKey:z62.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z62.object({mode:z62.literal("oauth"),integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),BindProjectChannelRequestSchema=z62.object({ref:z62.string().min(1),connectionAlias:z62.string().min(1).optional(),agentName:z62.string().min(1).max(160).nullable().optional(),force:z62.boolean().optional()}),ListProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1)}),SearchProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1),connectionAlias:z62.string().min(1),query:z62.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),connectionId:z62.uuid(),externalWorkspaceId:z62.string().min(1),externalChannelId:z62.string().min(1),externalChannelName:z62.string().nullable(),agentName:z62.string().nullable(),enabled:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z62.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z62.object({id:z62.string().min(1),name:z62.string().min(1),visibility:z62.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z62.string().min(1).nullable(),canMove:z62.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z62.object({markdown:z62.boolean().optional(),summary:z62.boolean().optional(),links:z62.boolean().optional(),branding:z62.boolean().optional(),images:z62.boolean().optional(),html:z62.union([z62.literal("cleaned"),z62.literal("raw"),z62.boolean()]).optional(),json:z62.union([z62.boolean(),z62.object({prompt:z62.string().min(1).max(1e4),schema:z62.record(z62.string(),z62.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z62.object({url:z62.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z62.object({query:z62.string().min(1),maxResults:z62.number().int().positive().max(20).optional(),sources:z62.array(z62.enum(["web","news","images"])).min(1).max(3).optional(),categories:z62.array(z62.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z62.enum(["hour","day","week","month","year"]).optional(),location:z62.string().min(1).max(160).optional(),country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(100).optional(),types:z62.array(z62.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),sources:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),passages:z62.number().int().min(1).max(5).optional(),skills:z62.literal("only").optional(),language:z62.string().min(1).optional(),topic:z62.string().min(1).optional(),license:z62.string().min(1).optional(),minStars:z62.number().int().min(0).optional(),maxStars:z62.number().int().min(0).optional(),archived:z62.boolean().optional(),fork:z62.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(500).optional(),authors:z62.array(z62.string().min(1)).min(1).optional(),categories:z62.array(z62.string().min(1)).min(1).optional(),from:z62.iso.date().optional(),to:z62.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),query:z62.string().min(1).max(500).optional(),maxPassages:z62.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),intent:z62.string().min(1).max(500),mode:z62.enum(["similar","citers","references"]).optional(),maxResults:z62.number().int().min(1).max(500).optional(),rerank:z62.boolean().optional(),anchors:z62.array(z62.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z62.object({url:z62.string().url(),search:z62.string().min(1).optional(),limit:z62.number().int().positive().max(200).optional(),includeSubdomains:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z62.object({url:z62.string().url(),limit:z62.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z62.object({text:z62.string().min(1).max(200).optional(),cron:z62.string().min(1).max(120).optional(),timezone:z62.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z62.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z62.union([z62.object({type:z62.enum(["scrape","crawl"]).default("scrape"),urls:z62.array(z62.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z62.object({type:z62.literal("search"),queries:z62.array(z62.string().min(1).max(256)).min(1).max(12),searchWindow:z62.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z62.number().int().min(1).max(50).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z62.object({name:z62.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),notification:z62.object({email:z62.object({enabled:z62.boolean().default(!0),recipients:z62.array(z62.string().email()).min(1).max(20),includeDiffs:z62.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z62.object({monitorId:z62.string().uuid(),name:z62.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),status:z62.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z62.object({monitorId:z62.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z62.string().uuid()}),RunProjectIntegrationToolRequestSchema=z62.object({tool:z62.string().min(1),input:z62.record(z62.string(),z62.unknown()),connectionAlias:z62.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z62.object({provider:z62.string().min(1),providerCredits:z62.number().nonnegative().optional(),providerCostUsd:z62.number().nonnegative().optional(),requests:z62.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z62.object({credits:z62.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),json:z62.unknown().optional(),branding:z62.record(z62.string(),z62.unknown()).optional(),warning:z62.string().optional()}),FirecrawlSearchToolOutputSchema=z62.object({query:z62.string(),provider:z62.literal("firecrawl"),warning:z62.string().optional(),results:z62.array(z62.object({title:z62.string(),url:z62.string(),snippet:z62.string().optional(),content:z62.string().optional(),score:z62.number().optional(),publishedAt:z62.string().optional()}))}),FirecrawlResearchPaperSchema=z62.object({paperId:z62.string(),primaryId:z62.string().optional(),ids:z62.record(z62.string(),z62.array(z62.string())).optional(),title:z62.string().optional(),abstract:z62.string().optional(),score:z62.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z62.object({text:z62.string(),score:z62.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(z62.object({id:z62.string(),type:z62.string().min(1).optional(),url:z62.string(),title:z62.string().optional(),passages:z62.array(z62.object({text:z62.string()}).passthrough())}).passthrough()),coverage:z62.record(z62.string(),z62.string()).optional(),reranked:z62.boolean().optional(),repos:z62.array(z62.record(z62.string(),z62.unknown())).optional(),sources:z62.array(z62.record(z62.string(),z62.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),paper:z62.record(z62.string(),z62.unknown()),paperId:z62.string().optional(),query:z62.string().optional(),passages:z62.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema),poolSize:z62.number().int().nonnegative(),truncated:z62.boolean(),note:z62.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),count:z62.number(),links:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),description:z62.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),total:z62.number(),pages:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),warning:z62.string().optional()})),warning:z62.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z62.object({cron:z62.string().optional(),text:z62.string().optional(),timezone:z62.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z62.object({id:z62.string().optional(),type:z62.enum(["scrape","crawl","search"]).optional(),urls:z62.array(z62.string()).optional(),queries:z62.array(z62.string()).optional(),searchWindow:z62.string().optional(),maxResults:z62.number().optional(),includeDomains:z62.array(z62.string()).optional(),excludeDomains:z62.array(z62.string()).optional(),scrapeOptions:z62.record(z62.string(),z62.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z62.object({id:z62.string(),name:z62.string(),status:z62.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z62.string().nullable().optional(),lastRunAt:z62.string().nullable().optional(),currentCheckId:z62.string().nullable().optional(),targets:z62.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z62.string().nullable().optional(),judgeEnabled:z62.boolean().optional(),estimatedCreditsPerMonth:z62.number().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z62.object({id:z62.string(),monitorId:z62.string(),scheduledFor:z62.string().nullable().optional(),startedAt:z62.string().nullable().optional(),finishedAt:z62.string().nullable().optional(),estimatedCredits:z62.number().optional(),reservedCredits:z62.number().optional(),actualCredits:z62.number().optional(),billingStatus:z62.string().nullable().optional(),summary:z62.object({totalPages:z62.number().optional(),same:z62.number().optional(),changed:z62.number().optional(),new:z62.number().optional(),removed:z62.number().optional(),error:z62.number().optional()}).passthrough().optional(),error:z62.string().nullable().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitors:z62.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),deleted:z62.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),checks:z62.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),check:FirecrawlMonitorCheckOutputSchema,next:z62.string().optional()}),FirecrawlToolKeySchema=z62.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z62.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),tool:z62.string().min(1),connectionAlias:z62.string().min(1).nullable().optional(),output:z62.record(z62.string(),z62.unknown()),executedAt:z62.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z62.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z62.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z62.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z62.array(ProjectChannelCandidateDTOSchema))}});import{z as z63}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z63.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z63.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z63.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z63.object({userId:z63.string().min(1),name:z63.string(),email:z63.string().min(1),subscribed:z63.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z63.object({maxSubscribers:z63.number().int().positive(),subscriberCount:z63.number().int().nonnegative(),effectiveRecipientCount:z63.number().int().nonnegative(),currentUserSubscribed:z63.boolean(),candidates:z63.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z63.object({userIds:z63.array(z63.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z63.object({topic:UserManagedNotificationTopicSchema,enabled:z63.boolean(),source:z63.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z63.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z63.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z63.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z63.string().nullable(),maskedEmail:z63.string().min(1),applied:z63.boolean(),expiresAt:z63.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z63.object({scheduleId:z63.string().min(1),scheduleName:z63.string(),projectId:z63.string().min(1),projectName:z63.string(),env:z63.string().min(1)}),FollowedSchedulesSchema=z63.object({schedules:z63.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z64}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common2();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z64.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=z64.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z64.uuid(),env:z64.string().min(1),name:z64.string().min(1),cron:z64.string().min(1),command:z64.string().min(1),secretKeys:z64.array(z64.string().min(1)),enabled:z64.boolean(),lastRunAt:z64.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z64.string().nullable(),overPolicyReasons:z64.array(z64.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120),cron:z64.string().min(1).max(120),command:z64.string().min(1).max(500),secretKeys:z64.array(ProjectSecretKeySchema).default([]),enabled:z64.boolean().optional()}),UpdateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120).optional(),cron:z64.string().min(1).max(120).optional(),command:z64.string().min(1).max(500).optional(),secretKeys:z64.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z64.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z64.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z64.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z64.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z64.object({maxRuns:z64.number().int().positive(),retentionDays:z64.number().int().positive().nullable(),outputRetentionDays:z64.number().int().positive(),maxOutputBytes:z64.number().int().positive()}),SchedulePolicyStateSchema=z64.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z64.object({code:z64.enum(["Free","PAYG","Premium","Pro"]),source:z64.enum(["cached_subscription","free_fallback"]),activeSchedules:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().nonnegative()}),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),concurrency:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().positive()}),compute:z64.object({settledMs:z64.number().int().nonnegative(),activeMs:z64.number().int().nonnegative(),reservedMs:z64.number().int().nonnegative().optional(),includedMs:z64.number().int().nonnegative(),remainingMs:z64.number().int().nonnegative(),resetsAt:z64.coerce.date()}),upgrade:z64.object({code:z64.literal("Pro"),activeSchedulesLimit:z64.number().int().positive(),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),maxConcurrentRuns:z64.number().int().positive(),computeIncludedMs:z64.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z64.array(z64.string())}),ProjectScheduleUsageSchema=z64.object({runCount:z64.number().int().nonnegative(),runsWithOutput:z64.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z64.object({id:z64.uuid(),scheduleId:z64.uuid(),projectId:z64.uuid(),env:z64.string().min(1),scheduleName:z64.string().min(1),command:z64.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z64.object({id:z64.string().min(1),name:z64.string().min(1)}).nullable(),queuedAt:z64.coerce.date(),startedAt:z64.coerce.date().nullable(),finishedAt:z64.coerce.date().nullable(),exitCode:z64.number().int().nullable(),errorCode:z64.string().nullable(),error:z64.string().nullable(),outputBytes:z64.number().int().nonnegative(),outputTruncated:z64.boolean(),outputExpiresAt:z64.coerce.date().nullable(),metadataExpiresAt:z64.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z64.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z64.coerce.date().nullable(),items:z64.array(z64.object({key:z64.string().min(1),updatedAt:z64.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z64.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z64.object({trigger:z64.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z64.object({limit:z64.coerce.number().int().min(1).max(100).default(25),cursor:z64.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z64.object({items:z64.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z64.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z64.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z64.object({items:z64.array(ProjectScheduleRunDTOSchema),nextCursor:z64.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z65}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z65.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z65.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z65.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z65.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("user"),userId:z65.string().min(1)}).strict(),z65.object({kind:z65.literal("agent"),agentKey:z65.string().min(1).max(120),agentId:z65.uuid().optional()}).strict(),z65.object({kind:z65.literal("system")}).strict()]),NotificationSummarySchema=z65.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z65.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z65.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z65.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z65.discriminatedUnion("topic",[z65.object({topic:z65.literal("agent_question"),questionId:z65.uuid(),title:z65.string().trim().min(1).max(80),description:z65.string().trim().min(1).max(240)}).strict(),z65.object({topic:z65.literal("agent_run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().optional(),proposalId:z65.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z65.object({id:z65.uuid(),projectId:z65.uuid(),sourceKey:z65.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z65.literal(1),payload:NotificationPayloadSchema,createdAt:z65.coerce.date()}),NotificationRecipientStateSchema=z65.object({id:z65.uuid(),notificationId:z65.uuid(),projectId:z65.uuid(),userId:z65.string().min(1),readAt:z65.coerce.date().nullable(),archivedAt:z65.coerce.date().nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationDeliveryStateSchema=z65.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z65.object({id:z65.uuid(),notificationRecipientId:z65.uuid(),projectId:z65.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z65.number().int().nonnegative(),nextAttemptAt:z65.coerce.date().nullable(),lastAttemptAt:z65.coerce.date().nullable(),sentAt:z65.coerce.date().nullable(),failureCode:z65.string().max(80).nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationPreferenceSchema=z65.object({topic:WorkNotificationTopicSchema,channel:z65.literal("email"),enabled:z65.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z65.enum(["default","explicit"])}),NotificationSubjectSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("question"),questionId:z65.uuid()}).strict(),z65.object({kind:z65.literal("run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z65.object({kind:z65.literal("retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().nullable(),proposalId:z65.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z65.object({kind:z65.literal("merge_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().nullable()}).strict()]),NotificationViewSchema=z65.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema2(NotificationViewSchema),NotificationListSchema=z65.object({items:z65.array(NotificationViewSchema),nextCursor:z65.string().nullable(),unreadCount:z65.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema2(NotificationListSchema),ListNotificationsQuerySchema=z65.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z65.string().min(1).max(120).optional(),sourceKey:z65.string().min(1).max(255).optional(),unread:z65.stringbool().optional(),archived:z65.stringbool().optional(),limit:z65.coerce.number().int().min(1).max(100).optional(),cursor:z65.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z65.object({recipient:NotificationRecipientStateSchema,unreadCount:z65.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema2(NotificationStateSchema),UpdateNotificationStateRequestSchema=z65.object({read:z65.boolean().optional(),archived:z65.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived."),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z65.object({enabled:z65.boolean(),pausedUntil:z65.coerce.date().nullable(),source:z65.enum(["default","explicit"]).optional()})}});import{z as z66}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,QUESTION_DIGEST_PREFERENCE_ENTRY_ID,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z66.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_question","work_review.agent_conflict","schedule.schedule_health","schedule.schedule_compute_allowance","usage.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z66.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z66.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z66.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z66.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z66.object({enabled:z66.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z66.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z66.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z66.enum(["work_review","schedule","usage"]),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z66.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),id:z66.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z66.literal("question_digest"),enabled:z66.boolean(),source:PreferenceSourceSchema,pausedUntil:z66.coerce.date().nullable()}).strict(),z66.object({kind:z66.literal("provider_subscription"),id:z66.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z66.literal("marketing"),name:z66.string(),description:z66.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z66.object({email:EmailNotificationPreferenceSchema,entries:z66.array(NotificationPreferenceEntrySchema),unavailableGroups:z66.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z66.object({enabled:z66.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),enabled:z66.boolean()}).strict(),z66.object({kind:z66.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),enabled:z66.boolean(),pauseDays:z66.number().int().min(1).max(MAX_QUESTION_DIGEST_PAUSE_DAYS).nullable().optional()}).strict().refine(body=>body.enabled||!body.pauseDays,"Pausing requires the toggle to be enabled."),z66.object({kind:z66.literal("provider_subscription"),enabled:z66.boolean()}).strict()])}});import{z as z67}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=z67.object({surface:SurfaceNameSchema,key:z67.string(),label:z67.string()}),InlineSchema=z67.object({text:z67.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z67.discriminatedUnion("type",[z67.object({type:z67.literal("paragraph"),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("preview"),ref:DiffRefSchema,caption:z67.string().optional()}),z67.object({type:z67.literal("code"),code:z67.string(),lang:z67.string().optional(),caption:z67.string().optional()}),z67.object({type:z67.literal("risk"),level:z67.enum(["warning","error"]),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("list"),items:z67.array(z67.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z67.object({headline:z67.string(),blocks:z67.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z67.object({summary:EnvDiffSummarySchema,fingerprint:z67.string(),generatedAt:z67.coerce.date(),cached:z67.boolean().optional(),credits:z67.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z68}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=z68.object({date:z68.string(),visitors:z68.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z68.object({key:z68.string(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z68.object({path:z68.string(),pageName:z68.string().nullable().optional(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z68.object({preset:z68.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z68.string(),requestedTo:z68.string(),effectiveFrom:z68.string(),effectiveTo:z68.string(),isRetentionLimited:z68.boolean(),groupBy:z68.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z68.object({date:z68.string(),content:z68.string(),updatedAt:z68.string(),updatedByUserId:z68.string()}),ProjectPageviewAnalyticsDTOSchema=z68.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative(),bounceRate:z68.number().min(0).max(100),viewsPerVisit:z68.number().nonnegative(),averageVisitDurationSeconds:z68.number().nonnegative(),visitorsSeries:z68.array(ProjectDailyVisitorsDTOSchema),topPages:z68.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z68.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z69}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_common2();init_create_dto();ProjectInviteDTOSchema=z69.object({id:z69.string(),email:z69.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z69.coerce.date(),createdAt:z69.coerce.date(),inviterUserId:z69.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z69.object({id:z69.string(),token:z69.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z69.object({success:z69.boolean(),projectId:z69.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z70}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=z70.object({id:z70.string(),name:z70.string(),image:z70.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z70.object({count:z70.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z70.object({counts:z70.object({signed_up:z70.int(),activated:z70.int()}),credits:z70.object({total:z70.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z70.email(),emailVerified:z70.boolean(),createdAt:z70.coerce.date(),updatedAt:z70.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z71}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common2();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z71.object({id:z71.string(),principalType:ProjectPrincipalTypeSchema,principalId:z71.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z71.coerce.date(),expiresAt:z71.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z71.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z71.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z71.record(z71.string(),z71.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z71.object({access:z71.array(ProjectAccessItemDTOSchema),invites:z71.array(ProjectInviteDTOSchema),organization:z71.object({name:z71.string().nullable(),logo:z71.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z71.object({success:z71.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z71.object({success:z71.boolean(),projectId:z71.uuid()}))}});import{z as z72}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common2();init_create_dto();PublicationStateDTOSchema=z72.object({publicationStatus:PublicationStatusSchema,appUrl:z72.string().nullable(),lastPublishedAt:z72.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z73}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z73.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z73.object({branch:BranchSchema,revision:z73.string().min(1).max(64).nullable(),generation:z73.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z73.url().nullable()})}});import{z as z74}from"zod";var PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,SandboxPullPhaseSchema,SandboxPullFailureCodeSchema,SandboxPullFailureSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewBridgePackageSchema=z74.object({name:z74.string().min(1),version:z74.string().min(1)}),PreviewBridgeCapabilitySchema=z74.object({integrated:z74.boolean(),packages:z74.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z74.object({url:z74.url(),expiresAt:z74.iso.datetime().nullable(),source:z74.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z74.object({name:z74.string().min(1),locator:z74.string().min(1).optional(),source:z74.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z74.object({kind:z74.literal("dependency_build_scripts_blocked"),packageManager:z74.enum(["pnpm","yarn","bun"]),packages:z74.array(z74.string()),targets:z74.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z74.string(),approvalKey:z74.string(),command:z74.string().optional(),approval:z74.object({id:z74.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z74.object({code:z74.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z74.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z74.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z74.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z74.object({message:z74.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z74.number().int().optional().catch(void 0),logTail:z74.array(z74.string()).optional().catch(void 0),logTailTruncated:z74.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z74.object({approvalId:z74.uuid()}),PreviewInstallPolicyApprovalEventSchema=z74.discriminatedUnion("type",[z74.object({type:z74.literal("progress"),step:z74.enum(["approval","install","restart","readiness"]),message:z74.string()}),z74.object({type:z74.literal("approved")}),z74.object({type:z74.literal("complete")}),z74.object({type:z74.literal("error"),code:z74.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z74.string()})])}});import{z as z75}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common2();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z75.string(),slug:z75.string().nullable(),logo:z75.string().nullable(),metadata:z75.record(z75.string(),z75.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z75.object({id:z75.string(),name:z75.string(),email:z75.email(),image:z75.string().nullable()}),OrganizationMemberDTOSchema=z75.object({id:z75.string(),userId:z75.string(),organizationId:z75.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z75.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z76}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common2();init_create_dto();init_response();CancellationReasonCodeSchema=z76.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z76.object({reason:CancellationReasonCodeSchema,details:z76.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z76.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z76.object({offerVersion:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),renewsOn:z76.string()}),PlanMigrationPreviewDTOSchema=z76.object({currency:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),startsAt:z76.string(),renewsAt:z76.string(),nextRenewalAmount:z76.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z76.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z76.object({id:z76.string(),organizationId:z76.string(),legacySubscriptionId:z76.string(),offeredPlanCode:z76.string(),offeredPlanName:z76.string(),offeredPriceAmount:z76.number(),offeredCurrency:z76.string(),offerVersion:z76.string(),state:PlanMigrationStateSchema,checkoutToken:z76.string().nullable(),deadlineAt:z76.string(),transitions:z76.array(z76.object({event:z76.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z76.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z76.object({included:z76.number().optional(),unitPrice:z76.number().optional(),dailyCap:z76.number().nullable().optional()}),EntitlementsDTOSchema=z76.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z76.object({retentionDays:z76.number().int().positive(),canUseExtendedDateRanges:z76.boolean()}).optional(),history:z76.object({retentionDays:z76.number().int().positive()}).optional(),members:z76.object({canInvite:z76.boolean(),maxMembers:z76.number().int().positive().nullable()}).optional(),projects:z76.object({maxProjects:z76.number().int().positive().nullable()}).optional(),domains:z76.object({canUseCustomDomains:z76.boolean(),maxDomains:z76.number().int().nonnegative().nullable()}).optional(),media_storage:z76.object({limitBytes:z76.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z76.object({usedBytes:z76.number().int().nonnegative().nullable(),limitBytes:z76.number().int().nonnegative().nullable(),state:z76.enum(["ready","unavailable"]),measuredAt:z76.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z76.object({toPlanCode:TemplateCodeSchema,effectiveAt:z76.string(),scheduledAt:z76.string().nullable()}),HostingOverageStatusDTOSchema=z76.object({state:z76.enum(["ready","unavailable"]),planCode:z76.string(),overageAvailable:z76.boolean(),overageEnabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().nullable(),periodStart:z76.iso.datetime().nullable(),periodEnd:z76.iso.datetime().nullable(),usedBytes:z76.number().nonnegative().nullable(),includedBytes:z76.number().nonnegative().nullable(),overageBytes:z76.number().nonnegative(),currentOverageAmountMicros:z76.number().nonnegative().nullable(),currency:z76.string().nullable(),status:z76.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z76.object({enabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling overages requires a monthly cap"}),SubscriptionDTOSchema=z76.object({id:z76.string(),external_id:z76.string(),customerId:z76.string(),planId:z76.string(),planCode:z76.union([TemplateCodeSchema,z76.literal("Unknown")]),currentPeriod:z76.object({start:z76.string(),end:z76.string().nullable()}),cancelAt:z76.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z76.string(),nextPaymentAt:z76.string().nullable(),baseAmount:z76.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z76.object({totalCap:z76.number(),dailyCap:z76.number(),usedTotal:z76.number()}),CreditBalanceDTOSchema=z76.object({total:z76.number(),base:z76.number(),dailyBase:z76.number(),purchases:z76.number(),awards:z76.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z76.object({total:z76.number(),nearLimit:z76.boolean(),canChat:z76.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z76.object({dailyFreeAvailable:z76.number(),monthlyAvailable:z76.number(),purchasedAvailable:z76.number(),awardedAvailable:z76.number()}),ProjectDailyCreditAllowanceDTOSchema=z76.object({periodCap:z76.number(),dailyGrant:z76.number(),usedThisPeriod:z76.number(),remainingThisPeriod:z76.number()}),ProjectCreditBalanceDTOSchema=z76.object({projectId:z76.uuid(),organizationId:z76.string(),balance:z76.object({totalAvailable:z76.number(),nearLimit:z76.boolean(),canUseAi:z76.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z76.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z76.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z76.object({planCode:z76.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z76.object({source:z76.enum(["cached_subscription","free_fallback"]),settledMs:z76.number().int().nonnegative(),activeMs:z76.number().int().nonnegative(),reservedMs:z76.number().int().nonnegative().optional(),includedMs:z76.number().int().positive(),remainingMs:z76.number().int().nonnegative(),resetsAt:z76.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().nonnegative(),refillAmountUsd:z76.number().nonnegative()}),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().nonnegative().nullable(),refillAmountUsd:z76.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().min(.01).multipleOf(.01),refillAmountUsd:z76.number().min(.01).multipleOf(.01)}).strict(),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z76.object({invoiceId:z76.string(),newBalance:z76.int(),creditCount:z76.int(),amountUsd:z76.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z76.object({url:z76.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema2(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema2(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema2(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema2(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema2(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema2(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema2(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema2(PortalDTOSchema)}});import{z as z77}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=z77.object({brand:z77.string(),last4:z77.string(),exp:z77.string(),isDefault:z77.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z78}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema2,EntryDTO,PaginatedEntriesDTOSchema2,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema2,EntryListResponseSchema,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema2,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema2,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema2,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common2();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z78.string().superRefine((path51,ctx)=>{let segments=path51.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=z78.object({type:z78.literal("renameField"),contentType:z78.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z78.object({enabled:z78.boolean()}).strict(),ContentFieldGroupSchema=z78.object({id:z78.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z78.string().min(1).max(255),default:z78.boolean().optional()}).strict(),ContentTypeDTOSchema=z78.object({id:z78.string(),name:z78.string(),label:z78.string(),isSingleton:z78.boolean(),i18n:ContentTypeI18nSchema,groups:z78.array(ContentFieldGroupSchema).default([]),fields:z78.record(z78.string(),FieldDefinitionSchema),createdAt:z78.string(),updatedAt:z78.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z78.object({contentTypes:z78.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z78.object({id:z78.string(),entryId:z78.string(),documentId:z78.string(),slug:z78.string(),locale:z78.string().optional(),createdAt:z78.string(),updatedAt:z78.string(),__fimo:z78.object({contentType:z78.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({limit:z78.number(),offset:z78.number(),total:z78.number(),hasMore:z78.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z78.object({contentType:z78.string(),count:z78.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z78.object({counts:z78.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z78.object({count:z78.number().int().nonnegative(),sourceLocale:z78.string(),targetLocale:z78.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z78.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z78.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z78.union([z78.string(),z78.number(),z78.boolean(),z78.null()]),entryWhereOperatorSchema2=z78.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z78.array(entryWhereScalarSchema2).optional(),$nin:z78.array(entryWhereScalarSchema2).optional(),$contains:z78.string().optional(),$startsWith:z78.string().optional(),$null:z78.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z78.object({data:z78.record(z78.string(),z78.unknown()),locale:z78.string().min(1).optional(),documentId:z78.uuid().optional()}),entryIdsSchema=z78.array(z78.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z78.object({sql:z78.string().min(1)}),BulkCreateEntriesRequestSchema=z78.object({entries:z78.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z78.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z78.object({updates:z78.array(z78.object({id:z78.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,locale:z78.string().min(1).optional()}),z78.object({where:EntryWhereSchema2,locale:z78.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z78.object({data:z78.array(z78.record(z78.string(),z78.unknown())),meta:z78.object({rowCount:z78.number().int().nonnegative(),truncated:z78.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({created:z78.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({updated:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({deleted:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z79}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z79.object({index:z79.number().int().nonnegative(),contentType:z79.string(),field:z79.string(),value:z79.string(),against:z79.enum(["stored","batch"]),ownerDocumentId:z79.uuid().optional(),ownerIndex:z79.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z79.object({code:z79.literal("unique_conflict"),message:z79.string(),conflicts:z79.array(UniqueConflictSchema),truncated:z79.boolean().optional()})}});import{z as z80}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=z80.object({kind:z80.literal("unique_conflict"),contentType:z80.string(),field:z80.string(),value:z80.string(),documentCount:z80.number().int().positive(),documentIds:z80.array(z80.uuid()),documentIdsTruncated:z80.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z80.object({code:z80.literal("schema_transition_rejected"),message:z80.string(),issues:z80.array(SchemaTransitionIssueSchema),truncated:z80.boolean().optional()})}});import{z as z81}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_common2();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z81.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z81.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z81.object({field:CmsFieldNameSchema,direction:z81.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z81.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z81.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z81.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z81.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z81.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z82}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z82.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z83}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z83.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z83.object({event:ClientTrackedEventSchema,properties:z83.record(z83.string(),z83.unknown()).default({})})}});import{z as z84}from"zod";var AssetPathItemSchema,AssetDTOSchema2,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema2,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common2();init_create_dto();init_response();AssetPathItemSchema=z84.object({id:z84.string(),name:z84.string()}),AssetDTOSchema2=z84.object({id:z84.string(),name:z84.string(),type:AssetTypeSchema,originalFileName:z84.string().nullable(),parentId:z84.string().nullable(),mimeType:z84.string().nullable(),fileSize:z84.number().nullable(),url:z84.string().nullable(),storageKey:z84.string().nullable(),createdAt:z84.string(),updatedAt:z84.string(),altText:z84.string().nullable().optional(),caption:z84.string().nullable().optional(),aiCaption:z84.string().nullable().optional(),aiAltText:z84.string().nullable().optional(),aiTags:z84.array(z84.string()).nullable().optional(),aiPrimaryColor:z84.string().nullable().optional(),aiProcessingStatus:z84.string().nullable().optional(),width:z84.number().nullable().optional(),height:z84.number().nullable().optional(),path:z84.array(AssetPathItemSchema).optional(),hasChildren:z84.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z84.lazy(()=>z84.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z84.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z84.object({error:z84.string(),code:z84.literal("media_storage_limit_exceeded"),usedBytes:z84.number().int().nonnegative(),limitBytes:z84.number().int().positive(),incomingBytes:z84.number().int().nonnegative()}),AssetReferenceScopeSchema=z84.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z84.object({assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z84.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z84.object({totalFiles:z84.number().int().nonnegative(),checkedFiles:z84.number().int().nonnegative(),limit:z84.number().int().positive()}),AssetReferenceFindingDTOSchema=z84.object({assetId:z84.uuid(),entryId:z84.string(),documentId:z84.string(),contentType:z84.string(),locale:z84.string().nullable(),slug:z84.string(),fieldPath:z84.string()}),AssetReferenceScopeResultDTOSchema=z84.object({scope:AssetReferenceScopeSchema,label:z84.string(),state:z84.enum(["available","not-published","failed"]),coverage:z84.enum(["complete","partial","failed"]),referenceCount:z84.number().int().nonnegative().optional(),codeReferenceCount:z84.number().int().nonnegative().optional(),referencedAssetIds:z84.array(z84.uuid()).optional(),references:z84.array(AssetReferenceFindingDTOSchema),reason:z84.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z84.discriminatedUnion("type",[z84.object({type:z84.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z84.object({type:z84.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z84.object({type:z84.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z84.object({replacementAssetId:z84.uuid()}),AssetReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),entriesChanged:z84.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),filesChanged:z84.number().int().nonnegative(),commitSha:z84.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z84.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z84.object({error:z84.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z84.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z84.object({intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z84.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z84.object({id:z84.uuid(),intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()),replacementAssetId:z84.uuid().nullable(),expiresAt:z84.iso.datetime(),undoable:z84.boolean(),requestedByMe:z84.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z84.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z84.object({error:z84.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z85}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z85.object({key:z85.string(),value:z85.string().optional(),defaultValue:z85.string(),locale:z85.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z86}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=z86.object({id:z86.string(),name:z86.string(),type:z86.enum(["file","folder"]),path:z86.string(),children:z86.lazy(()=>z86.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z86.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z86.object({path:z86.string(),exists:z86.boolean(),type:z86.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z87}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema2,FormUpdateSchema2,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z87.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z87.object({minLength:z87.number().optional(),maxLength:z87.number().optional(),min:z87.number().optional(),max:z87.number().optional(),pattern:z87.string().optional(),maxFileSize:z87.number().optional(),accept:z87.array(z87.string()).optional()}),FormFieldSchema=z87.object({type:FormFieldTypeSchema,label:z87.string(),placeholder:z87.string().optional(),required:z87.boolean().optional(),defaultValue:z87.string().optional(),options:z87.array(z87.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z87.record(z87.string(),FormFieldSchema),FormContentSchema2=z87.object({name:z87.string().min(1).max(255),label:z87.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z88}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z88.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z88.object({items:z88.array(ProjectMessagePublicDTOSchema),nextCursor:z88.string().nullable()}),ChatLiveTurnDTOSchema=z88.object({invocationId:z88.string(),step:z88.enum(["preparing","working","compacting","merging"]),startedAt:z88.string()}),ChatLiveTurnStateDTOSchema=z88.object({threadId:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z88.object({id:z88.string(),role:z88.enum(["user","assistant"]),parts:z88.array(z88.unknown()),metadata:z88.record(z88.string(),z88.unknown()).nullable(),versionId:z88.string().nullable().optional(),createdAt:z88.date().transform(value=>value.toISOString()),providerMessageId:z88.string().nullable().optional(),invocationId:z88.string().nullable().optional(),invocationStatus:z88.string().nullable().optional(),invocationTerminalReason:z88.string().nullable().optional()}),ChatAttentionDTOSchema=z88.object({type:z88.literal("merge_conflict"),merge:z88.object({mergeId:z88.string().uuid(),projectId:z88.string(),fromBranch:z88.string(),toBranch:z88.string()}),publishAfterMerge:z88.boolean()}),ChatThreadMessagesPageDTOSchema=z88.object({threadId:z88.string().nullable(),title:z88.string().nullable(),messages:z88.array(ChatThreadMessageDTOSchema),nextCursor:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z88.object({kind:z88.literal("replay"),threadId:z88.string(),userMessageId:z88.string()}),ChatQueuedOutcomeDTOSchema=z88.object({kind:z88.literal("queued"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string()}),ChatBusyOutcomeDTOSchema=z88.object({kind:z88.literal("busy"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string().optional()}),ChatRefusedOutcomeDTOSchema=z88.object({kind:z88.literal("refused"),threadId:z88.string(),userMessageId:z88.string(),refusedInvocationId:z88.string(),terminalReason:z88.string()}),ChatNonStreamingOutcomeDTOSchema=z88.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z88.object({success:z88.boolean(),deletedCount:z88.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema2(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z88.object({code:z88.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z88.string()})}});import{z as z89}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common2();init_create_dto();init_response();UploadResultDTOSchema=z89.object({url:z89.string().url(),key:z89.string(),size:z89.number(),contentType:z89.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z90}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=z90.object({canAccess:z90.boolean(),permissions:z90.record(z90.string(),z90.boolean()),role:z90.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z91}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:z91.string().trim().default(""),sort:z91.enum(["recent","name","relevance"]).default("recent"),category:z91.string().optional()})}});import{z as z92}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_common2();init_create_dto();init_response();DomainStatusSchema=z92.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z92.enum(["fimo","external"]),PaymentStatusSchema=z92.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z92.object({id:z92.string().uuid(),domain:z92.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z92.boolean(),price:z92.number().int().nullable(),renewalPrice:z92.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z92.string().nullable(),failureReason:z92.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z92.object({domain:z92.string(),available:z92.boolean(),premium:z92.boolean(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),purchaseType:z92.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z92.object({domain:z92.string(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),premium:z92.boolean(),allowedYears:z92.array(z92.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z92.object({firstName:z92.string().max(100),lastName:z92.string().max(100),companyName:z92.string().max(100).optional(),address1:z92.string().max(255),address2:z92.string().max(255).optional(),city:z92.string().max(100),state:z92.string().max(100),zip:z92.string().max(20),country:z92.string().max(2),phone:z92.string().max(30),email:z92.union([z92.string().email().max(255),z92.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z92.object({firstName:z92.string().min(1).max(100),lastName:z92.string().min(1).max(100),companyName:z92.string().max(100).optional(),address1:z92.string().min(1).max(255),address2:z92.string().max(255).optional(),city:z92.string().min(1).max(100),state:z92.string().min(1).max(100),zip:z92.string().min(1).max(20),country:z92.string().min(1).max(2),phone:z92.string().min(1).max(30),email:z92.string().email().max(255)}),SearchDomainsRequestSchema=z92.object({keyword:z92.string().min(1).max(100),tldFilter:z92.array(z92.string()).optional()}),CheckAvailabilityRequestSchema=z92.object({domains:z92.array(z92.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=z92.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z92.object({domain:DomainNameSchema,years:z92.number().int().min(1).max(10).optional().default(3),autoRenew:z92.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z92.object({autoRenew:z92.boolean().optional()}),RenewDomainRequestSchema=z92.object({years:z92.number().int().min(1).max(10).optional().default(1),autoRenew:z92.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z92.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z92.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z92.object({verified:z92.boolean(),email:z92.string().nullable(),verifyBy:z92.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z93}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_common2();init_create_dto();init_response();ProjectDomainStatusSchema=z93.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=z93.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=z93.object({txtName:z93.string().nullable().optional(),txtValue:z93.string().nullable().optional(),httpUrl:z93.string().nullable().optional(),httpBody:z93.string().nullable().optional(),cname:z93.string().nullable().optional(),cnameTarget:z93.string().nullable().optional()}),SSLValidationErrorSchema=z93.object({message:z93.string()}),OwnershipVerificationSchema=z93.object({type:z93.string(),name:z93.string(),value:z93.string()}),ProjectDomainSSLDTOSchema=z93.object({status:z93.string(),method:z93.string().nullable(),type:z93.string().nullable(),validationRecords:z93.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z93.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z93.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z93.enum(["subdomain","apex"]),RedirectConfigSchema=z93.object({type:z93.literal("apex_to_www"),linkedDomainId:z93.string()}).nullable().optional(),ProjectDomainDTOSchema=z93.object({id:z93.string(),hostname:z93.string(),status:z93.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z93.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z93.string(),scdCnameTarget:z93.string().optional(),apexTargets:z93.array(z93.string()),dnsAutoConfigured:z93.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z93.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z93.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z93.object({hostname:z93.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:z93.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z93.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z93.object({available:z93.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z93.object({success:z93.boolean(),hostname:z93.string()}))}});import{z as z94}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=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z94.object({available:z94.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z94.object({slug:z94.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z94.object({subdomain:z94.string(),subdomainUpdatedAt:z94.coerce.date()})),SubdomainSuggestionsQuerySchema=z94.object({base:z94.string().max(100).optional(),max:z94.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z94.object({suggestions:z94.array(z94.string())}))}});import{z as z95}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z95.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z95.object({code:ProjectTransferBlockerCodeSchema,message:z95.string(),count:z95.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z95.object({targetOrganizationId:z95.string().min(1)}),ProjectTransferResultDTO=createDTO(z95.object({projectId:z95.string(),sourceOrganizationId:z95.string(),targetOrganizationId:z95.string(),movedThreads:z95.number().int().nonnegative(),revokedInvites:z95.number().int().nonnegative(),revokedGrants:z95.number().int().nonnegative(),preservedGrants:z95.number().int().nonnegative(),warnings:z95.array(z95.string())}))}});import{z as z96}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema2,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema2,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z96.object({translated:z96.number().int().nonnegative(),total:z96.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z96.object({locale:z96.string(),isDefault:z96.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z96.object({defaultLocale:z96.string(),locales:z96.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z96.object({locale:z96.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z96.object({locale:z96.string().min(1).max(40)}),ProjectLocaleMutationSchema=z96.object({locale:z96.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z96.object({locale:z96.string(),entriesDeleted:z96.number().int().nonnegative(),labelsDeleted:z96.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z97}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=z97.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z97.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=z97.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z97.number(),credits:z97.number().optional(),billingMode:z97.enum(["fimo-credits","provider-account"]).optional(),confidence:z97.enum(["exact","estimated","metered"]),basis:z97.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z98}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema2,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=z98.object({options:z98.record(z98.string(),z98.unknown()),name:z98.string().optional(),parentId:z98.string().nullable().optional(),altText:z98.string().optional(),caption:z98.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z98.string().min(1).optional(),model:z98.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=z98.object({jobId:z98.string(),status:z98.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z98.string().nullable().optional(),credits:z98.number().optional(),costUsd:z98.number().optional(),billingMode:z98.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z98.object({error:z98.string(),code:z98.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:z98.array(GenerationTaskIdSchema).optional(),availableModels:z98.array(z98.string()).optional(),issues:z98.array(z98.unknown()).optional()})}});import{z as z99}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=z99.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z99.object({name:z99.string(),key:z99.string(),description:z99.string(),type:FlagTypeSchema,required:z99.boolean(),defaultValue:z99.unknown().optional(),enumValues:z99.array(z99.string()).optional(),isArray:z99.boolean()}),AssetModelPriceSchema=z99.object({unitPrice:z99.number(),unit:z99.string(),confidence:z99.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z99.object({id:z99.string(),shortName:z99.string(),provider:z99.string(),source:z99.string(),modality:z99.enum(["image","video","audio"]),tags:z99.array(z99.string()),displayName:z99.string(),description:z99.string(),flags:z99.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z99.object({model:z99.string(),costUsd:z99.number(),credits:z99.number(),billingMode:z99.enum(["fimo-credits","provider-account"]),confidence:z99.enum(["exact","estimated","metered"]),basis:z99.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z100}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=z100.object({tourId:z100.string(),version:z100.string(),status:z100.string(),completedAt:z100.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z100.array(UserTourDTOSchema))}});import{z as z101}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=z101.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z101.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z101.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z101.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z101.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z101.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z101.enum(["user","agent","system"]),SupportReportTagSchema=z101.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z101.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z101.object({organization:z101.object({id:z101.string().trim().min(1).max(255),name:z101.string().trim().max(240).optional()}),project:z101.object({id:z101.uuid(),name:z101.string().trim().max(240).optional(),createdAt:z101.coerce.date().optional()}).optional(),environment:z101.string().trim().max(255).optional(),clientVersion:z101.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z101.object({message:z101.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z101.string().trim().max(200).optional(),limit:z101.coerce.number().int().min(1).max(100).default(50),offset:z101.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z101.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z101.uuid().nullable().optional(),note:z101.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=z101.object({message:z101.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z101.object({kind:SupportReportLinkKindSchema,label:z101.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z101.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z101.object({kind:SupportReportActorKindSchema,id:z101.string().nullable(),name:z101.string().nullable()}),SupportReportLinkDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportLinkKindSchema,label:z101.string(),url:SupportReportHttpUrlSchema,externalId:z101.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportEventKindSchema,body:z101.string().nullable(),metadata:z101.record(z101.string(),z101.unknown()),actor:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z101.object({id:z101.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z101.array(z101.string()),source:SupportReportSourceSchema,message:z101.string(),reporter:z101.object({id:z101.string().nullable(),name:z101.string().nullable(),email:z101.string().nullable()}),organization:z101.object({id:z101.string().nullable(),name:z101.string()}),project:z101.object({id:z101.uuid().nullable(),name:z101.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z101.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z101.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z101.string().nullable(),deliveredAt:z101.coerce.date().nullable()}).nullable(),duplicateOfReportId:z101.uuid().nullable(),resolvedAt:z101.coerce.date().nullable(),createdAt:z101.coerce.date(),updatedAt:z101.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z101.string().nullable(),clientVersion:z101.string().nullable(),links:z101.array(SupportReportLinkDTOSchema),events:z101.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z101.object({reports:z101.array(SupportReportSummaryDTOSchema),total:z101.number().int().nonnegative(),statusCounts:z101.object({new:z101.number().int().nonnegative(),in_progress:z101.number().int().nonnegative(),waiting:z101.number().int().nonnegative(),resolved:z101.number().int().nonnegative(),duplicate:z101.number().int().nonnegative(),irrelevant:z101.number().int().nonnegative(),ignored:z101.number().int().nonnegative()}),limit:z101.number().int().positive(),offset:z101.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z101.object({id:z101.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z101.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z102}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=z102.iso.datetime({offset:!0}).pipe(z102.coerce.date()),OpsRecentChatInputSchema=z102.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z102.string().trim().min(1).max(255).optional(),limit:z102.coerce.number().int().min(1).max(200).default(100),cursor:z102.string().trim().min(1).max(2e3).optional(),slim:z102.boolean().default(!0),reason:z102.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=z102.object({id:z102.string(),threadId:z102.string(),providerMessageId:z102.string().nullable(),invocationId:z102.string().nullable(),env:z102.string().nullable(),role:z102.string(),parts:z102.array(z102.record(z102.string(),z102.unknown())),metadata:z102.object({status:z102.string().optional(),traceUrl:z102.string().optional(),externalFileChanges:z102.array(z102.unknown()).optional()}),stats:z102.object({toolCount:z102.number().int().nonnegative(),failedToolCount:z102.number().int().nonnegative()}),createdAt:z102.iso.datetime({offset:!0}),project:z102.object({id:z102.string(),name:z102.string(),displayName:z102.string().nullable(),organizationId:z102.string().nullable()})}),OpsRecentChatResponseSchema=z102.object({target:z102.object({backendProfile:OpsBackendProfileSchema,projectEnv:z102.string().nullable()}),window:z102.object({from:z102.iso.datetime({offset:!0}),to:z102.iso.datetime({offset:!0})}),messages:z102.object({items:z102.array(OpsRecentChatMessageSchema),nextCursor:z102.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z103}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z103.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z103.literal(!1),reason:z103.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z104}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z104.object({packageManager:z104.string().trim().min(1).max(200).nullable(),trackedLockfiles:z104.array(z104.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z104.string().trim().min(1)}),OpsProjectPackageManagerSchema=z104.object({target:z104.object({backendProfile:OpsBackendProfileSchema,projectId:z104.uuid(),projectEnv:z104.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z105}from"zod";var OPS_AGENT_BRANCH_DISCARD_LIMIT,OpsAgentBranchAllowlistSchema,OpsAgentBranchRecoveredOwnerSchema,OpsAgentBranchDiscardPlanInputSchema,OpsAgentBranchDiscardApplyInputSchema,OPS_AGENT_BRANCH_DISCARD_BLOCKERS,OpsAgentBranchDiscardBlockerSchema,init_ops_agent_branch_discard_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-branch-discard.dto.js"(){"use strict";init_env();OPS_AGENT_BRANCH_DISCARD_LIMIT=25,OpsAgentBranchAllowlistSchema=z105.array(BranchSchema).min(1,"name at least one Branch to discard").max(OPS_AGENT_BRANCH_DISCARD_LIMIT).refine(branches=>new Set(branches).size===branches.length,{error:"the Branch allowlist must not repeat a Branch"}),OpsAgentBranchRecoveredOwnerSchema=z105.object({branch:BranchSchema,sessionId:z105.uuid()}),OpsAgentBranchDiscardPlanInputSchema=z105.object({branches:OpsAgentBranchAllowlistSchema,reason:z105.string().trim().min(1).max(1e3),recoveredOwners:z105.array(OpsAgentBranchRecoveredOwnerSchema).max(OPS_AGENT_BRANCH_DISCARD_LIMIT).optional()}).refine(input=>(input.recoveredOwners??[]).every(owner=>input.branches.includes(owner.branch)),{error:"every recovered owner must name a Branch from the allowlist",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.branch)).size===owners.length},{error:"recovered owners must not repeat a Branch",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.sessionId)).size===owners.length},{error:"recovered owners must not repeat a session",path:["recoveredOwners"]}),OpsAgentBranchDiscardApplyInputSchema=OpsAgentBranchDiscardPlanInputSchema.safeExtend({planHash:z105.string().trim().length(64)}),OPS_AGENT_BRANCH_DISCARD_BLOCKERS=["branch_not_found","not_agent_session_branch","branch_not_active","production_branch","default_branch","production_source_branch","owner_session_missing","not_project_agent_run","open_merge","live_mcp_session","live_owner","has_descendants","recovery_direct_owner_present","recovery_session_not_found","recovery_session_not_project_agent_run","recovery_session_not_terminal","recovery_session_already_bound"],OpsAgentBranchDiscardBlockerSchema=z105.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z106}from"zod";function createAgentRunWebhookEventDataSchema(status){return z106.object({run:z106.object({id:z106.string(),agentName:z106.string(),trigger:z106.string(),status:z106.literal(status),startedAt:z106.string().nullable(),finishedAt:z106.string().nullable(),reason:z106.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,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_common2();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z106.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z106.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z106.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z106.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z106.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z106.object({reason:WebhookEntryChangeReasonSchema,operationId:z106.string().optional(),batch:z106.object({index:z106.number().int().positive(),total:z106.number().int().positive()}).optional(),changes:z106.array(z106.object({action:WebhookEntryChangeActionSchema,contentType:z106.string(),id:z106.string(),documentId:z106.string(),locale:z106.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z106.object({form:z106.object({id:z106.string(),label:z106.string()}),submission:z106.object({id:z106.string(),data:z106.record(z106.string(),z106.unknown()),submittedAt:z106.string()})}),PublishStartedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("publishing"),startedAt:z106.string()})}),PublishSucceededWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("published"),url:z106.string(),publishedAt:z106.string(),firstPublish:z106.boolean()})}),PublishFailedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("failed"),reason:z106.string()})}),PublishUnpublishedWebhookEventDataSchema=z106.object({publication:z106.object({previousUrl:z106.string(),unpublishedAt:z106.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z106.object({review:z106.object({runId:z106.string(),agentName:z106.string(),reason:z106.string()}),source:z106.object({branch:z106.string(),revision:z106.string(),anchorBranch:z106.string()})}),AgentReviewResolvedWebhookEventDataSchema=z106.object({review:z106.object({id:z106.string(),runId:z106.string(),agentName:z106.string(),resolution:z106.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z106.object({report:z106.object({weekStart:z106.string(),weekEnd:z106.string(),pageviews:z106.number(),visitors:z106.number(),previousPageviews:z106.number(),previousVisitors:z106.number()})}),MediaAssetWebhookEventDataSchema=z106.object({id:z106.string().nullable(),name:z106.string().nullable(),type:z106.string(),mimeType:z106.string().nullable(),fileSize:z106.number().nullable()}),MediaUploadedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("updated")}),MediaDeletedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string()})}),LabelChangedWebhookEventDataSchema=z106.object({changes:z106.array(z106.object({action:z106.enum(["created","updated","deleted"]),key:z106.string(),locale:z106.string(),value:z106.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),isDefault:z106.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),previousCode:z106.string()})}),LocaleDeletedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),entriesDeleted:z106.number().int().nonnegative(),labelsDeleted:z106.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z106.object({merge:z106.object({id:z106.string(),from:BranchSchema,to:BranchSchema,applied:z106.array(z106.object({surface:SurfaceNameSchema,count:z106.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z106.object({branch:z106.object({name:BranchSchema}),version:z106.object({versionId:z106.uuid(),name:z106.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,"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,"branch.restored":BranchRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z106.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z106.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z106.discriminatedUnion("source",[z106.object({source:z106.literal("literal"),value:z106.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z106.object({source:z106.literal("secret"),key:z106.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z106.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z106.object({name:z106.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z106.object({name:z106.string(),source:z106.enum(["literal","secret"]),secretKey:z106.string().nullable(),secretPrefix:z106.string().nullable(),configured:z106.literal(!0)}),WebhookFilterSchema=z106.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z106.string().min(1).max(255).optional(),agentName:z106.string().min(1).max(120).optional(),mediaType:z106.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z106.string().min(1).max(255).optional(),locale:z106.string().min(1).max(120).optional()}),JsonValueSchema=z106.lazy(()=>z106.union([z106.string(),z106.number(),z106.boolean(),z106.null(),z106.array(JsonValueSchema),z106.record(z106.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z106.url(),enabled:z106.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z106.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z106.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z106.url().optional(),enabled:z106.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z106.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z106.boolean().optional()}),TestProjectWebhookRequestSchema=z106.object({eventType:WebhookEventTypeSchema.optional(),data:z106.record(z106.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z106.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z106.uuid(),name:z106.string(),eventType:WebhookEventTypeSchema,enabled:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z106.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z106.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z106.coerce.date().nullable(),deliveryStats24h:z106.object({succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z106.uuid(),projectId:z106.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z106.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z106.number().int().positive(),test:z106.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z106.number().int().nonnegative(),responseStatus:z106.number().int().nullable(),lastErrorCode:z106.string().nullable(),lastErrorMessage:z106.string().nullable(),payloadAvailable:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z106.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z106.string().nullable(),qstashMessageId:z106.string().nullable(),deliveredAt:z106.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z106.object({items:z106.array(WebhookDeliveryDTOSchema),pagination:z106.object({page:z106.number().int().positive(),limit:z106.number().int().positive(),total:z106.number().int().nonnegative(),totalPages:z106.number().int().positive(),hasMore:z106.boolean()}),stats:z106.object({total:z106.number().int().nonnegative(),succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z106.object({id:z106.uuid(),deliveryId:z106.uuid(),attempt:z106.number().int().positive(),status:z106.enum(["delivering","succeeded","failed"]),responseStatus:z106.number().int().nullable(),durationMs:z106.number().int().nonnegative(),responseExcerpt:z106.string().nullable(),errorCode:z106.string().nullable(),errorMessage:z106.string().nullable(),createdAt:z106.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z106.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z106.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z107}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z107.object({key:z107.literal("fimo-2"),enabled:z107.boolean(),dismissed:z107.boolean().default(!1),interacted:z107.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z108}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_common2();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z108.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z108.object({total:z108.number(),base:z108.number(),purchases:z108.number(),awards:z108.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z108.object({id:z108.string(),name:z108.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z108.object({type:z108.string(),brand:z108.string().nullable(),last4:z108.string().nullable(),expirationDate:z108.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z108.object({currency:z108.string(),nextPaymentAmount:z108.number().nullable(),nextPaymentAt:z108.string().nullable(),billingInterval:z108.string().nullable(),totalAmount:z108.number().nullable(),discountAmount:z108.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z108.object({id:z108.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z108.string().nullable(),currentPeriodEndsAt:z108.string().nullable(),renewsAt:z108.string().nullable(),cancelAt:z108.string().nullable(),renewAutomatically:z108.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z108.object({type:z108.enum(["low_balance","critical_balance","approaching_limit"]),message:z108.string(),estimatedPromptsRemaining:z108.number().nullable(),avgCostPerPrompt:z108.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z108.object({monthlyCredits:z108.number().nullable(),usedThisPeriod:z108.number(),remainingThisPeriod:z108.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z108.object({organizationId:z108.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z108.string().nullable(),tenureDays:z108.number().int().nonnegative(),capturedAt:z108.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z108.object({hasSubscription:z108.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z108.number().nullable(),alerts:z108.array(CreditAlertDTOSchema),portalUrl:z108.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z108.object({creditCount:z108.number().int().positive(),expiresAt:z108.string().datetime().nullable().optional(),message:z108.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("free"),amountCents:z108.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("purchase"),amountCents:z108.number().int().positive()}),CreditTopupRequestDTOSchema=z108.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z108.object({success:z108.boolean(),transactionId:z108.string().nullable(),newBalance:z108.number(),creditCount:z108.number(),type:z108.enum(["free","purchase"]),invoiceId:z108.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z109}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=z109.object({totalCredits:z109.number(),totalCostUsd:z109.number(),totalMessages:z109.number(),avgCostPerMessage:z109.number(),periodStart:z109.string().nullable(),periodEnd:z109.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z109.object({date:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z109.array(UsageByUserForProjectDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z109.object({summary:UsageSummaryDTOSchema,byProject:z109.array(UsageByProjectDTOSchema),byUser:z109.array(UsageByUserDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z110}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=z110.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z110.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z110.object({startDate:z110.string().optional(),endDate:z110.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z110.coerce.number().int().positive().default(1),limit:z110.coerce.number().int().positive().max(100).default(20),sortBy:z110.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z110.string().optional(),activeOnly:z110.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z110.object({totalCredits:z110.number(),totalCostUsd:z110.number(),totalMessages:z110.number(),avgCostPerMessage:z110.number(),avgCreditsPerMessage:z110.number(),periodStart:z110.string(),periodEnd:z110.string(),creditsChange:z110.number().nullable(),costChange:z110.number().nullable(),messagesChange:z110.number().nullable(),unattributedCredits:z110.number(),unattributedCostUsd:z110.number(),unattributedMessages:z110.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z110.object({date:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z110.object({organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number(),projectCount:z110.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z110.object({userId:z110.string(),userName:z110.string().nullable(),userEmail:z110.string().nullable(),userImage:z110.string().nullable(),organizationId:z110.string().nullable(),organizationName:z110.string().nullable(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),projectCount:z110.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z110.object({projectId:z110.string(),projectName:z110.string(),projectDisplayName:z110.string().nullable(),organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z110.object({id:z110.string(),name:z110.string(),value:z110.number(),percentage:z110.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z110.object({day:z110.number(),hour:z110.number(),value:z110.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z110.object({summary:UsageOverviewSummaryDTOSchema,timeline:z110.array(UsageTimelinePointDTOSchema),topOrganizations:z110.array(OrganizationUsageRowDTOSchema),topUsers:z110.array(UserUsageRowDTOSchema),topProjects:z110.array(ProjectUsageRowDTOSchema),creditDistribution:z110.array(UsageDistributionItemDTOSchema),userDistribution:z110.array(UsageDistributionItemDTOSchema),heatmap:z110.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z110.object({page:z110.number(),limit:z110.number(),totalItems:z110.number(),totalPages:z110.number(),hasMore:z110.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z110.object({organizations:z110.array(OrganizationUsageRowDTOSchema),top:z110.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z110.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z110.object({users:z110.array(ExtendedUserUsageRowDTOSchema),top:z110.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z110.object({projects:z110.array(ExtendedProjectUsageRowDTOSchema),top:z110.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z110.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z110.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z110.object({credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),createdAt:z110.string(),memberCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z110.object({id:z110.string(),name:z110.string().nullable(),email:z110.string(),image:z110.string().nullable(),createdAt:z110.string(),organizationCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),displayName:z110.string().nullable(),createdAt:z110.string(),organizationId:z110.string(),organizationName:z110.string(),ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z111}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=z111.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z111.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z111.object({command:z111.string().min(1).max(1e4),cwd:z111.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z111.record(z111.string(),z111.string()).optional(),name:z111.string().optional(),waitForCompletion:z111.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z111.object({identifier:z111.string(),status:SandboxProcessStatusSchema,command:z111.string().optional(),startedAt:z111.string().optional(),exitCode:z111.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z111.object({processes:z111.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z111.object({processId:z111.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z111.object({success:z111.boolean(),message:z111.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z112}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common2();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_control_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_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_hosted_preview_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_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_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_transfer_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_branch_discard_dto();init_webhook_dto();init_preview_feature_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(["symbolic-ref","--short","-q","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 resolveBranchFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{branch:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||!isValidBranch(branch)?null:{branch,source:"branch"}}catch{return null}}function resolveBranchFromEnvironment(){let branch=process.env.FIMO_ENV?.trim();return branch&&isValidBranch(branch)?branch: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 branch,source,readOnly=!1;if(opts.branchOverride!==void 0){if(!isValidBranch(opts.branchOverride))throw new InvalidBranchOverrideError(opts.branchOverride);branch=opts.branchOverride,source="flag"}else{let fromGit=await resolveBranchFromGit(cwd);if(fromGit)branch=fromGit.branch,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{let fromEnvironment=resolveBranchFromEnvironment();if(!fromEnvironment)throw new GitBranchUndetectedError;branch=fromEnvironment,source="environment"}}if(opts.fimo&&branch!=="prod")try{let{data:branches}=await opts.fimo.execute("branches.list",{projectId:settings.projectId,includeAgentBranches:!0}),names=branches.map(candidate=>candidate.branch);if(!names.includes(branch)&&source==="flag")throw new BranchNotFoundError(branch,names)}catch(err){if(err instanceof BranchNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,branch,source,readOnly:readOnly||void 0}}function branchSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--branch":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"FIMO_ENV",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 Branch: ${ctx.branch} (from ${sourceHint}${ro})`}function branchOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let branch=cur.opts().branch;if(typeof branch=="string"&&branch.length>0)return branch;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let branchOverride2=branchOverrideFromCommand(cmd),cfg=loadConfig(),baseFimo=createCliFimoClient(cfg),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2,fimo:baseFimo});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${branchSourceBanner(ctx)}
199
+ `)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z46.enum(REPORT_TONES),blockCommon={title:z46.string().trim().min(1).max(120).optional(),fallback:z46.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z46.object({type:z46.literal("text"),...blockCommon,text:z46.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z46.object({type:z46.literal("metric"),...blockCommon,items:z46.array(z46.object({value:z46.string().trim().min(1).max(24),unit:z46.string().trim().min(1).max(12).optional(),label:z46.string().trim().min(1).max(160),note:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z46.array(z46.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z46.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z46.object({type:z46.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z46.string().trim().min(1).max(12).optional(),points:z46.array(z46.object({label:z46.string().trim().min(1).max(24),value:z46.number().finite(),highlight:z46.boolean().optional()}).strict()).min(2).max(24),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z46.object({type:z46.literal("list"),...blockCommon,items:z46.array(z46.object({tone:ReportToneSchema.optional(),label:z46.string().trim().min(1).max(24).optional(),heading:z46.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z46.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z46.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z46.object({type:z46.literal("table"),...blockCommon,columns:z46.array(z46.object({label:z46.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z46.array(z46.object({cells:z46.array(z46.object({text:z46.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z46.object({type:z46.literal("media"),...blockCommon,assetId:z46.uuid(),alt:z46.string().trim().min(1).max(300),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z46.object({type:z46.literal("links"),...blockCommon,items:z46.array(z46.object({label:z46.string().trim().min(1).max(120),url:z46.url({protocol:/^https$/}).max(2e3),description:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z46.object({type:z46.literal("code"),...blockCommon,language:z46.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z46.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z46.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z46.object({title:z46.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z46.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z46.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z46.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(normalizeReportDocument,"normalizeReportDocument");__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z47}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z47.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z47.object({dev:z47.string().trim().min(1).optional(),build:z47.string().trim().min(1).optional(),install:z47.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z47.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z47.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z47.object({type:z47.enum(["header","cookie","query","host"]),key:z47.string().min(1).optional(),value:z47.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z47.array(FimoHostingConditionSchema).min(1).optional(),missing:z47.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),permanent:z47.boolean().optional(),statusCode:z47.union([z47.literal(301),z47.literal(302),z47.literal(307),z47.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z47.object({source:z47.string().min(1),headers:z47.array(z47.object({key:z47.string().min(1),value:z47.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z47.object({rewrites:z47.array(FimoHostingRewriteSchema).optional(),redirects:z47.array(FimoHostingRedirectSchema).optional(),headers:z47.array(FimoHostingHeaderSchema).optional(),cleanUrls:z47.boolean().optional(),trailingSlash:z47.boolean().optional()}).strict(),FimoAppConfigSchema=z47.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path51){return[...path51.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path51){return pageRouteParamNames(path51).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z48}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common2();init_env();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-6-astra","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z48.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z48.string(),displayName:z48.string().nullable(),subdomain:z48.string().nullable().optional(),subdomainUpdatedAt:z48.date().nullable().optional(),organizationId:z48.string().nullable(),createdBy:z48.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z48.boolean().default(!0),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z48.string(),thumbnailUrl:z48.string().nullable(),publishedThumbnailUrl:z48.string().nullable(),category:z48.string().nullable(),snapshotUrl:z48.string().startsWith("/").optional(),appUrl:z48.string().nullable(),lastPublishedAt:z48.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z48.object({name:z48.string().optional(),previewEnabled:z48.boolean().optional(),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z48.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z48.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z48.object({id:z48.uuid(),name:z48.string(),displayName:z48.string().nullable(),thumbnailUrl:z48.string().nullable(),category:z48.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z48.object({id:z48.string(),name:z48.string(),avatar:z48.string().nullable(),color:z48.object({bg:z48.string(),text:z48.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z48.object({path:z48.string(),content:z48.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z48.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z48.object({id:z48.string(),messageId:z48.string(),versionId:z48.string().nullable(),role:ProjectChatMessageRole,parts:z48.array(z48.any()),createdAt:z48.coerce.date()}),MessageUserMetadataSchema=z48.object({id:z48.string(),name:z48.string().nullable().optional(),image:z48.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z48.number(),metadata:z48.object({user:MessageUserMetadataSchema,changeManifest:z48.array(z48.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z48.object({versionId:z48.uuid(),commitHash:z48.string(),name:z48.string(),description:z48.string().nullable(),kind:z48.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z48.object({versionCount:z48.number().int().nonnegative(),snapshotBytes:z48.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z48.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z48.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z48.object({content:z48.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z48.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z48.object({success:z48.boolean(),message:z48.string().optional(),warning:z48.string().optional(),durationMs:z48.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z48.object({isPublished:z48.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z48.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z48.object({label:z48.string().trim().min(1).max(120).optional(),notes:z48.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z48.object({success:z48.boolean(),message:z48.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z48.boolean(),publicationId:z48.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z49}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common2();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z49.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z49.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z49.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z49.string().nullable(),deletedAt:z49.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z49.object({id:z49.union([z49.literal(PREVIEW_ENVIRONMENT_KEY),z49.uuid()]),name:z49.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z49.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z49.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z49.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z49.object({surface:z49.enum(["code","schemas","content","translations","assets","forms"]),status:z49.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z49.number().int().nonnegative(),conflictCount:z49.number().int().nonnegative()}),BranchDiffResultSchema=z49.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z49.coerce.date(),surfaces:z49.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z50}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z50.object({projectId:z50.uuid(),name:z50.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z50.literal("production"),sourceBranch:BranchSchema,isPublished:z50.boolean(),url:z50.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PREVIEW_ENVIRONMENT_KEY),kind:z50.literal("preview"),matchedBranchCount:z50.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z50.literal("custom"),matchedBranchCount:z50.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z50.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z50.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z50.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z50.object({deletedId:z50.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z51}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z51.object({kind:z51.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z51.object({kind:z51.enum(["variable","secret"]),value:z51.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z51.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z51.object({kind:z51.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),key:z51.string(),kind:z51.literal("secret"),exposure:z51.literal("private"),environment:EnvironmentKeySchema,maskedValue:z51.string().optional(),createdAt:z51.date().transform(value=>value.toISOString()),updatedAt:z51.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z51.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z52}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=z52.object({success:z52.literal(!0),downloadUrl:z52.string(),expiresAt:z52.string(),fileSize:z52.number(),duration:z52.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z52.object({success:z52.literal(!0),projectId:z52.string(),projectName:z52.string(),displayName:z52.string(),projectUrl:z52.string(),duration:z52.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z52.object({contentTypes:z52.number(),entries:z52.number(),assets:z52.number(),translations:z52.number(),forms:z52.number(),codeFiles:z52.number(),assetFiles:z52.number()}),ImportPreviewSurfaceDTOSchema=z52.object({name:z52.string(),included:z52.boolean(),count:z52.number().optional(),note:z52.string().optional()}),ImportPreviewDTOSchema=z52.object({projectName:z52.string(),displayName:z52.string().nullable(),category:z52.string().nullable(),exportedAt:z52.string(),version:z52.string(),envScope:z52.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z52.array(ImportPreviewSurfaceDTOSchema),fileSize:z52.number(),fileName:z52.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z52.object({success:z52.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z53}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=z53.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z53.object({type:z53.literal("manual")}),ScheduleTriggerSchema=z53.object({type:z53.literal("schedule"),cron:z53.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:z53.string().optional()}),WebhookTriggerSchema2=z53.object({type:z53.literal("webhook"),path:z53.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z53.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z54}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=z54.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z54.object({token:z54.string().min(1),risk:CapabilityRiskTierSchema,description:z54.string()}),AgentSubAgentSummarySchema=z54.object({name:z54.string().min(1),grant:z54.enum(["inherit","explicit"]),effectiveCaps:z54.array(z54.string().min(1))}),AgentInstallSummaryDTOSchema=z54.object({agentName:z54.string().min(1),env:z54.string().min(1),declaredCapabilities:z54.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z54.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z54.array(CapabilitySummaryEntrySchema),criticalCapabilities:z54.array(CapabilitySummaryEntrySchema),subAgents:z54.array(AgentSubAgentSummarySchema),declaresDelegate:z54.boolean(),cycle:z54.array(z54.string()).nullable(),missingSubAgents:z54.array(z54.string()),warnings:z54.array(z54.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z55}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z55.object({kind:TriggerKindSchema,summary:z55.string()}),AgentListItemTriggerStateSchema=z55.object({triggerIndex:z55.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z55.boolean(),wired:z55.boolean(),syncError:z55.string().nullable()}),AgentListItemDTOSchema=z55.object({name:z55.string().min(1),description:z55.string().nullable(),goalFirstLine:z55.string().nullable(),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),triggers:z55.array(AgentListItemTriggerSchema),triggerStates:z55.array(AgentListItemTriggerStateSchema),paused:z55.boolean(),nextRunAt:z55.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z55.array(AgentListItemDTOSchema))}});import{z as z56}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z56.object({paused:z56.boolean(),cancelledRuns:z56.number().int().nonnegative(),stopIncomplete:z56.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema)}});import{z as z57}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z57.object({args:z57.unknown().optional(),requestId:z57.string().min(1).max(128).optional()}),DispatchSkippedSchema=z57.object({skipped:z57.enum(["no-manual-trigger","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])}),DispatchAcceptedSchema=z57.object({sessionId:z57.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z57.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z58}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z58.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z58.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z58.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z58.object({verb:SurfaceDeltaVerbSchema,key:z58.string(),detail:z58.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z58.record(z58.string(),z58.unknown()).optional()}),PerSurfaceDeltaSchema=z58.object({surface:SurfaceNameSchema,status:z58.enum(["ok","timed_out","failed","unchanged"]),durationMs:z58.number().int().nonnegative().optional(),changedCount:z58.number().int().nonnegative(),conflictCount:z58.number().int().nonnegative(),items:z58.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z58.boolean().optional(),error:z58.string().optional()}),CrossSurfaceFindingSchema=z58.object({id:z58.string(),kind:z58.string(),description:z58.string(),severity:z58.enum(["warning","error"]),source:z58.object({surface:SurfaceNameSchema,key:z58.string()}),target:z58.object({surface:SurfaceNameSchema,key:z58.string()}),actions:z58.array(z58.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z58.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z58.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),agents:z58.array(z58.object({id:z58.string(),name:z58.string(),status:z58.enum(["active","paused","failed"]),lastRunAt:z58.coerce.date().nullable()})).optional(),crossSurface:z58.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z58.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),crossSurface:z58.array(CrossSurfaceFindingSchema).optional(),fingerprint:z58.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z58.object({path:z58.string(),state:z58.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z58.string(),additions:z58.number().int().nonnegative(),deletions:z58.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z58.object({oid:z58.string().optional(),content:z58.string().optional(),truncated:z58.boolean(),binary:z58.boolean()}),CodeConflictDetailSchema=z58.object({path:z58.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z58.string(),targetTipSha:z58.string(),mergeBaseSha:z58.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z58.object({id:z58.string(),slug:z58.string(),contentType:z58.string(),data:z58.record(z58.string(),z58.unknown()),updatedAt:z58.coerce.date()}),ContentRowDiffSchema=z58.object({collection:z58.string(),rowId:z58.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z58.object({name:z58.string(),label:z58.string(),isSingleton:z58.boolean(),fields:z58.record(z58.string(),z58.unknown())}),SchemaTypeDiffSchema=z58.object({typeName:z58.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z58.object({id:z58.string(),name:z58.string(),type:z58.enum(["file","folder"]),mimeType:z58.string().nullable(),storageKey:z58.string().nullable(),url:z58.string().nullable(),fileSize:z58.number().nullable(),width:z58.number().nullable(),height:z58.number().nullable(),altText:z58.string().nullable(),caption:z58.string().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),AssetDiffSchema=z58.object({assetId:z58.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z58.object({locale:z58.string(),key:z58.string(),parent:z58.string().nullable(),child:z58.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z58.object({formName:z58.string(),label:z58.string().nullable(),schemaFingerprint:z58.string(),fields:z58.record(z58.string(),z58.unknown()),settings:z58.record(z58.string(),z58.unknown()).optional()}),FormSchemaDiffSchema=z58.object({formName:z58.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema2(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z58.enum(CONFLICT_KINDS),ConflictSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),kind:ConflictKindSchema.optional(),description:z58.string(),parentValue:z58.unknown().optional(),childValue:z58.unknown().optional(),conflictingFields:z58.array(z58.string()).optional(),code:z58.object({path:z58.string(),unresolvable:z58.boolean().optional(),reason:z58.string().optional()}).optional()}),FieldPickSchema=z58.object({field:z58.string(),choice:z58.enum(["parent","child","pick","ai-pick"]),pickedValue:z58.unknown().optional(),aiSessionId:z58.string().optional()}),ConflictResolutionSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),choice:z58.enum(["parent","child","pick"]),pickedValue:z58.unknown().optional(),fieldPicks:z58.array(FieldPickSchema).optional()}),MergeResultSchema=z58.object({ok:z58.boolean(),mergeId:z58.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()})),conflicts:z58.array(ConflictSchema).optional(),summary:z58.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z58.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z58.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z58.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z58.boolean().optional()}),ResolvedStrategySchema=z58.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z58.boolean()}),MergeRequestSchema=z58.object({from:BranchSchema,allowDirectMerge:z58.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z58.object({mergeId:z58.string().uuid(),streamUrl:z58.string(),strategy:ResolvedStrategySchema,acceptedAt:z58.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z58.object({mergeId:z58.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z58.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z58.array(ConflictSchema),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedBy:z58.string().nullable(),lastEditedAt:z58.coerce.date().nullable(),initiator:z58.object({userId:z58.string().nullable(),role:z58.string().nullable(),agentName:z58.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z58.object({resolutions:z58.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z58.object({mergeId:z58.string().uuid(),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedAt:z58.coerce.date(),lastEditedBy:z58.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z58.object({mergeId:z58.string().uuid(),resolutions:z58.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z58.object({mergeId:z58.string().uuid()}),PublishReleaseRequestSchema=z58.object({version:z58.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z58.string().max(2e4).optional()}),PublishReleaseResultSchema=z58.object({releaseTag:z58.string(),sha:z58.string(),publishedAt:z58.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z59}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z59.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z59.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z59.strictObject({branch:BranchSchema.optional(),project_agents_only:z59.coerce.boolean().optional(),agent_name:z59.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z59.coerce.date().optional(),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(200).default(25),cursor:z59.coerce.date().optional()}),SessionMetricsSchema=z59.object({cpuMs:z59.number().nonnegative().default(0),netBytes:z59.number().nonnegative().default(0),walltimeMs:z59.number().nonnegative().default(0),llmTokensIn:z59.number().nonnegative().optional(),llmTokensOut:z59.number().nonnegative().optional(),stepCount:z59.number().int().nonnegative().optional(),toolCallCounts:z59.record(z59.string().min(1).max(120),z59.number().int().nonnegative()).optional(),toolCallOutcomes:z59.array(z59.object({toolName:z59.string().min(1).max(120),success:z59.boolean(),code:z59.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z59.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z59.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z59.object({capturedAt:z59.coerce.date(),fingerprint:z59.string().min(1).max(256),counts:z59.object({code:z59.number().int().nonnegative(),content:z59.number().int().nonnegative(),schemas:z59.number().int().nonnegative(),labels:z59.number().int().nonnegative(),assets:z59.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z59.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z59.object({diff:DiffReportSchema,code:z59.array(CodeFileDiffSchema.extend({raw:z59.string().max(24576)})).max(200),schemas:z59.array(SchemaTypeDiffSchema).max(200),content:z59.array(z59.object({key:z59.string().min(1).max(512),collection:z59.string().min(1).max(256),slug:z59.string().max(512).optional(),verb:z59.enum(["added","modified","deleted"]),fields:z59.array(z59.object({name:z59.string().min(1).max(256),before:z59.unknown().optional(),after:z59.unknown().optional()})).max(20)})).max(200),labels:z59.array(z59.object({key:z59.string().min(1).max(512),locale:z59.string().min(1).max(64).optional(),before:z59.unknown().nullable(),after:z59.unknown().nullable()})).max(200),assets:z59.array(z59.object({key:z59.string().min(1).max(512),name:z59.string().min(1).max(512),verb:z59.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z59.strictObject({id:z59.uuid(),projectId:z59.uuid(),branch:BranchSchema,agentName:z59.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z59.unknown().optional(),capabilities:z59.array(z59.string()).optional(),dataSources:z59.array(z59.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z59.string().nullable(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),cancelledAt:z59.coerce.date().nullable(),costUsd:z59.number().nonnegative(),costCeilingUsd:z59.number().nonnegative(),creditsUsed:z59.number().int().nonnegative().nullable(),limitCredits:z59.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),longRunning:z59.boolean(),lastCheckpointId:z59.uuid().nullable(),agentBranchId:z59.uuid().nullable(),parentSessionId:z59.uuid().nullable(),terminalReason:z59.string().nullable(),errorMessage:z59.string().nullable(),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z59.string().nullable(),retainedBranch:BranchSchema.nullable().optional(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z59.object({id:z59.uuid(),sessionId:z59.uuid(),checkpointIdx:z59.number().int().nonnegative(),payloadRef:z59.string(),payloadSizeBytes:z59.number().int().nonnegative(),checksum:z59.string().length(64),createdAt:z59.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z59.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z59.object({session:AgentSessionDTOSchema,checkpoints:z59.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z59.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z59.object({reason:z59.string().min(1).max(120).optional()})}});import{z as z60}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=z60.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z60.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z60.object({id:z60.uuid(),envId:z60.uuid(),sessionId:z60.uuid().nullable(),skillName:z60.string().min(1),classification:AgentBranchClassificationSchema,rationale:z60.string().nullable(),summary:z60.string().nullable(),surfaceDeltas:z60.record(z60.string(),z60.unknown()),createdAt:z60.coerce.date(),decidedAt:z60.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z60.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z60.object({path:z60.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z60.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z60.object({code:z60.literal("merge_conflict"),message:z60.string(),conflicts:z60.record(z60.string(),z60.number().int().nonnegative())})}});import{z as z61}from"zod";function agentQuestionCapabilityDecision(request,answer){let answers=answer?.answer.questions??[],decision={requested:[],approved:[],denied:[]};return request.block.steps.forEach((step,index)=>{if(step.body.type!=="capabilities")return;let answered=answers.find(item=>item.stepId===step.id)??answers[index],selected=new Set(answered?.selectedLabels??[]);for(let item of step.body.items)decision.requested.push(item),(selected.has(item.label)?decision.approved:decision.denied).push(item.token)}),decision}var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z61.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z61.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z61.object({description:z61.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z61.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z61.object({id:z61.uuid(),projectId:z61.uuid(),threadId:z61.uuid(),invocationId:z61.uuid(),agentKey:z61.string().min(1).max(120),anchorEnv:z61.string().min(1).max(64),retainedEnv:z61.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z61.string().min(1).nullable(),continuationInvocationId:z61.uuid().nullable(),askedAt:z61.coerce.date(),expiresAt:z61.coerce.date(),closedAt:z61.coerce.date().nullable()});__name(agentQuestionCapabilityDecision,"agentQuestionCapabilityDecision");AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z61.object({questionId:z61.uuid(),invocationId:z61.uuid(),askedAt:z61.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z61.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z61.object({question:AgentQuestionSchema,continuationInvocationId:z61.uuid(),deduped:z61.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z62}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z62.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z62.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z62.enum(["secret_text"]),IntegrationCredentialUsageSchema=z62.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z62.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z62.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z62.object({mode:IntegrationAuthModeSchema,label:z62.string().min(1),description:z62.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z62.object({id:z62.string().min(1),label:z62.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z62.boolean()}),IntegrationToolDefinitionDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),description:z62.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z62.object({title:z62.string().min(1),description:z62.string().min(1),command:z62.string().min(1).optional()}),IntegrationInfoDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),type:z62.enum(["native","mcp"]).optional(),url:z62.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z62.array(IntegrationAuthModeDTOSchema),credentials:z62.array(IntegrationCredentialDefinitionDTOSchema),tools:z62.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z62.enum(["available","unavailable"]).optional(),connectionCapabilities:z62.object({customIdentityCreation:z62.boolean()}).optional(),recipes:z62.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),installed:z62.boolean(),enabled:z62.boolean(),setupState:z62.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z62.string().nullable(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),connectionStatus:z62.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),installedAt:z62.coerce.date().nullable(),updatedAt:z62.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),enabled:z62.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z62.string(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z62.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z62.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z62.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z62.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z62.object({id:z62.uuid(),organizationId:z62.string().min(1),integrationKey:z62.string().min(1),registrationId:z62.uuid().nullable(),alias:z62.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z62.string().min(1),externalAccountName:z62.string().nullable(),externalBotUserId:z62.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z62.array(z62.string()),connectedAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z62.boolean(),isDefault:z62.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z62.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z62.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z62.record(McpHeaderNameSchema,z62.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z62.object({alias:z62.string().min(1).max(120).optional(),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z62.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z62.object({displayName:z62.string().trim().min(1).max(35),backgroundColor:z62.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z62.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),alias:z62.string().min(1).max(120),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}),z62.object({mode:z62.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z62.boolean().optional(),registrationId:z62.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z62.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z62.union([z62.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z62.object({type:z62.literal("mcp"),name:z62.string().trim().min(1).max(120),url:z62.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z62.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z62.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z62.object({integrationKey:z62.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z62.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("oauth"),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),ReusableMcpServerAuthKindSchema=z62.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z62.object({id:z62.uuid(),name:z62.string().min(1),host:z62.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z62.string().min(1),availability:z62.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z62.object({query:z62.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z62.object({serverId:z62.uuid()}),LinearOAuthApplicationDistributionSchema=z62.enum(["private","public"]),OrganizationLinearAppDTOSchema=z62.object({id:z62.uuid(),displayName:z62.string().min(1),description:z62.string().nullable(),iconUrl:z62.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z62.enum(["active","revoked"]),connectionIds:z62.array(z62.uuid()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z62.object({appName:z62.string().trim().min(2).max(80),description:z62.string().trim().max(1e3).optional(),iconUrl:z62.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z62.object({projectId:z62.uuid(),registrationId:z62.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z62.object({integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),integrationKey:z62.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z62.object({mode:z62.literal("oauth"),integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),BindProjectChannelRequestSchema=z62.object({ref:z62.string().min(1),connectionAlias:z62.string().min(1).optional(),agentName:z62.string().min(1).max(160).nullable().optional(),force:z62.boolean().optional()}),ListProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1)}),SearchProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1),connectionAlias:z62.string().min(1),query:z62.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),connectionId:z62.uuid(),externalWorkspaceId:z62.string().min(1),externalChannelId:z62.string().min(1),externalChannelName:z62.string().nullable(),agentName:z62.string().nullable(),enabled:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z62.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z62.object({id:z62.string().min(1),name:z62.string().min(1),visibility:z62.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z62.string().min(1).nullable(),canMove:z62.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z62.object({markdown:z62.boolean().optional(),summary:z62.boolean().optional(),links:z62.boolean().optional(),branding:z62.boolean().optional(),images:z62.boolean().optional(),html:z62.union([z62.literal("cleaned"),z62.literal("raw"),z62.boolean()]).optional(),json:z62.union([z62.boolean(),z62.object({prompt:z62.string().min(1).max(1e4),schema:z62.record(z62.string(),z62.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z62.object({url:z62.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z62.object({query:z62.string().min(1),maxResults:z62.number().int().positive().max(20).optional(),sources:z62.array(z62.enum(["web","news","images"])).min(1).max(3).optional(),categories:z62.array(z62.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z62.enum(["hour","day","week","month","year"]).optional(),location:z62.string().min(1).max(160).optional(),country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(100).optional(),types:z62.array(z62.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),sources:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),passages:z62.number().int().min(1).max(5).optional(),skills:z62.literal("only").optional(),language:z62.string().min(1).optional(),topic:z62.string().min(1).optional(),license:z62.string().min(1).optional(),minStars:z62.number().int().min(0).optional(),maxStars:z62.number().int().min(0).optional(),archived:z62.boolean().optional(),fork:z62.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(500).optional(),authors:z62.array(z62.string().min(1)).min(1).optional(),categories:z62.array(z62.string().min(1)).min(1).optional(),from:z62.iso.date().optional(),to:z62.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),query:z62.string().min(1).max(500).optional(),maxPassages:z62.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),intent:z62.string().min(1).max(500),mode:z62.enum(["similar","citers","references"]).optional(),maxResults:z62.number().int().min(1).max(500).optional(),rerank:z62.boolean().optional(),anchors:z62.array(z62.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z62.object({url:z62.string().url(),search:z62.string().min(1).optional(),limit:z62.number().int().positive().max(200).optional(),includeSubdomains:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z62.object({url:z62.string().url(),limit:z62.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z62.object({text:z62.string().min(1).max(200).optional(),cron:z62.string().min(1).max(120).optional(),timezone:z62.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z62.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z62.union([z62.object({type:z62.enum(["scrape","crawl"]).default("scrape"),urls:z62.array(z62.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z62.object({type:z62.literal("search"),queries:z62.array(z62.string().min(1).max(256)).min(1).max(12),searchWindow:z62.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z62.number().int().min(1).max(50).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z62.object({name:z62.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),notification:z62.object({email:z62.object({enabled:z62.boolean().default(!0),recipients:z62.array(z62.string().email()).min(1).max(20),includeDiffs:z62.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z62.object({monitorId:z62.string().uuid(),name:z62.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),status:z62.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z62.object({monitorId:z62.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z62.string().uuid()}),RunProjectIntegrationToolRequestSchema=z62.object({tool:z62.string().min(1),input:z62.record(z62.string(),z62.unknown()),connectionAlias:z62.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z62.object({provider:z62.string().min(1),providerCredits:z62.number().nonnegative().optional(),providerCostUsd:z62.number().nonnegative().optional(),requests:z62.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z62.object({credits:z62.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),json:z62.unknown().optional(),branding:z62.record(z62.string(),z62.unknown()).optional(),warning:z62.string().optional()}),FirecrawlSearchToolOutputSchema=z62.object({query:z62.string(),provider:z62.literal("firecrawl"),warning:z62.string().optional(),results:z62.array(z62.object({title:z62.string(),url:z62.string(),snippet:z62.string().optional(),content:z62.string().optional(),score:z62.number().optional(),publishedAt:z62.string().optional()}))}),FirecrawlResearchPaperSchema=z62.object({paperId:z62.string(),primaryId:z62.string().optional(),ids:z62.record(z62.string(),z62.array(z62.string())).optional(),title:z62.string().optional(),abstract:z62.string().optional(),score:z62.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z62.object({text:z62.string(),score:z62.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(z62.object({id:z62.string(),type:z62.string().min(1).optional(),url:z62.string(),title:z62.string().optional(),passages:z62.array(z62.object({text:z62.string()}).passthrough())}).passthrough()),coverage:z62.record(z62.string(),z62.string()).optional(),reranked:z62.boolean().optional(),repos:z62.array(z62.record(z62.string(),z62.unknown())).optional(),sources:z62.array(z62.record(z62.string(),z62.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),paper:z62.record(z62.string(),z62.unknown()),paperId:z62.string().optional(),query:z62.string().optional(),passages:z62.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema),poolSize:z62.number().int().nonnegative(),truncated:z62.boolean(),note:z62.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),count:z62.number(),links:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),description:z62.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),total:z62.number(),pages:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),warning:z62.string().optional()})),warning:z62.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z62.object({cron:z62.string().optional(),text:z62.string().optional(),timezone:z62.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z62.object({id:z62.string().optional(),type:z62.enum(["scrape","crawl","search"]).optional(),urls:z62.array(z62.string()).optional(),queries:z62.array(z62.string()).optional(),searchWindow:z62.string().optional(),maxResults:z62.number().optional(),includeDomains:z62.array(z62.string()).optional(),excludeDomains:z62.array(z62.string()).optional(),scrapeOptions:z62.record(z62.string(),z62.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z62.object({id:z62.string(),name:z62.string(),status:z62.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z62.string().nullable().optional(),lastRunAt:z62.string().nullable().optional(),currentCheckId:z62.string().nullable().optional(),targets:z62.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z62.string().nullable().optional(),judgeEnabled:z62.boolean().optional(),estimatedCreditsPerMonth:z62.number().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z62.object({id:z62.string(),monitorId:z62.string(),scheduledFor:z62.string().nullable().optional(),startedAt:z62.string().nullable().optional(),finishedAt:z62.string().nullable().optional(),estimatedCredits:z62.number().optional(),reservedCredits:z62.number().optional(),actualCredits:z62.number().optional(),billingStatus:z62.string().nullable().optional(),summary:z62.object({totalPages:z62.number().optional(),same:z62.number().optional(),changed:z62.number().optional(),new:z62.number().optional(),removed:z62.number().optional(),error:z62.number().optional()}).passthrough().optional(),error:z62.string().nullable().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitors:z62.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),deleted:z62.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),checks:z62.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),check:FirecrawlMonitorCheckOutputSchema,next:z62.string().optional()}),FirecrawlToolKeySchema=z62.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z62.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),tool:z62.string().min(1),connectionAlias:z62.string().min(1).nullable().optional(),output:z62.record(z62.string(),z62.unknown()),executedAt:z62.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z62.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z62.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z62.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z62.array(ProjectChannelCandidateDTOSchema))}});import{z as z63}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z63.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z63.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z63.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z63.object({userId:z63.string().min(1),name:z63.string(),email:z63.string().min(1),subscribed:z63.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z63.object({maxSubscribers:z63.number().int().positive(),subscriberCount:z63.number().int().nonnegative(),effectiveRecipientCount:z63.number().int().nonnegative(),currentUserSubscribed:z63.boolean(),candidates:z63.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z63.object({userIds:z63.array(z63.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z63.object({topic:UserManagedNotificationTopicSchema,enabled:z63.boolean(),source:z63.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z63.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z63.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z63.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z63.string().nullable(),maskedEmail:z63.string().min(1),applied:z63.boolean(),expiresAt:z63.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z63.object({scheduleId:z63.string().min(1),scheduleName:z63.string(),projectId:z63.string().min(1),projectName:z63.string(),env:z63.string().min(1)}),FollowedSchedulesSchema=z63.object({schedules:z63.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z64}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common2();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z64.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=z64.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z64.uuid(),env:z64.string().min(1),name:z64.string().min(1),cron:z64.string().min(1),command:z64.string().min(1),secretKeys:z64.array(z64.string().min(1)),enabled:z64.boolean(),lastRunAt:z64.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z64.string().nullable(),suspendedAt:z64.coerce.date().nullable().optional(),suspensionReason:z64.string().nullable().optional(),overPolicyReasons:z64.array(z64.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120),cron:z64.string().min(1).max(120),command:z64.string().min(1).max(500),secretKeys:z64.array(ProjectSecretKeySchema).default([]),enabled:z64.boolean().optional()}),UpdateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120).optional(),cron:z64.string().min(1).max(120).optional(),command:z64.string().min(1).max(500).optional(),secretKeys:z64.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z64.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z64.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z64.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z64.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z64.object({maxRuns:z64.number().int().positive(),retentionDays:z64.number().int().positive().nullable(),outputRetentionDays:z64.number().int().positive(),maxOutputBytes:z64.number().int().positive()}),SchedulePolicyStateSchema=z64.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z64.object({code:z64.enum(["Free","PAYG","Premium","Pro"]),source:z64.enum(["cached_subscription","free_fallback"]),activeSchedules:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().nonnegative()}),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),concurrency:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().positive()}),compute:z64.object({settledMs:z64.number().int().nonnegative(),activeMs:z64.number().int().nonnegative(),reservedMs:z64.number().int().nonnegative().optional(),includedMs:z64.number().int().nonnegative(),remainingMs:z64.number().int().nonnegative(),resetsAt:z64.coerce.date()}),upgrade:z64.object({code:z64.literal("Pro"),activeSchedulesLimit:z64.number().int().positive(),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),maxConcurrentRuns:z64.number().int().positive(),computeIncludedMs:z64.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z64.array(z64.string())}),ProjectScheduleUsageSchema=z64.object({runCount:z64.number().int().nonnegative(),runsWithOutput:z64.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z64.object({id:z64.uuid(),scheduleId:z64.uuid(),projectId:z64.uuid(),env:z64.string().min(1),scheduleName:z64.string().min(1),command:z64.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z64.object({id:z64.string().min(1),name:z64.string().min(1)}).nullable(),queuedAt:z64.coerce.date(),startedAt:z64.coerce.date().nullable(),finishedAt:z64.coerce.date().nullable(),exitCode:z64.number().int().nullable(),errorCode:z64.string().nullable(),error:z64.string().nullable(),outputBytes:z64.number().int().nonnegative(),outputTruncated:z64.boolean(),outputExpiresAt:z64.coerce.date().nullable(),metadataExpiresAt:z64.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z64.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z64.coerce.date().nullable(),items:z64.array(z64.object({key:z64.string().min(1),updatedAt:z64.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z64.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z64.object({trigger:z64.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z64.object({limit:z64.coerce.number().int().min(1).max(100).default(25),cursor:z64.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z64.object({items:z64.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z64.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z64.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z64.object({items:z64.array(ProjectScheduleRunDTOSchema),nextCursor:z64.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z65}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z65.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z65.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z65.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z65.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("user"),userId:z65.string().min(1)}).strict(),z65.object({kind:z65.literal("agent"),agentKey:z65.string().min(1).max(120),agentId:z65.uuid().optional()}).strict(),z65.object({kind:z65.literal("system")}).strict()]),NotificationSummarySchema=z65.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z65.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z65.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z65.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z65.discriminatedUnion("topic",[z65.object({topic:z65.literal("agent_question"),questionId:z65.uuid(),title:z65.string().trim().min(1).max(80),description:z65.string().trim().min(1).max(240)}).strict(),z65.object({topic:z65.literal("agent_run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().optional(),proposalId:z65.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z65.object({id:z65.uuid(),projectId:z65.uuid(),sourceKey:z65.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z65.literal(1),payload:NotificationPayloadSchema,createdAt:z65.coerce.date()}),NotificationRecipientStateSchema=z65.object({id:z65.uuid(),notificationId:z65.uuid(),projectId:z65.uuid(),userId:z65.string().min(1),readAt:z65.coerce.date().nullable(),archivedAt:z65.coerce.date().nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationDeliveryStateSchema=z65.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z65.object({id:z65.uuid(),notificationRecipientId:z65.uuid(),projectId:z65.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z65.number().int().nonnegative(),nextAttemptAt:z65.coerce.date().nullable(),lastAttemptAt:z65.coerce.date().nullable(),sentAt:z65.coerce.date().nullable(),failureCode:z65.string().max(80).nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationPreferenceSchema=z65.object({topic:WorkNotificationTopicSchema,channel:z65.literal("email"),enabled:z65.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z65.enum(["default","explicit"])}),NotificationSubjectSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("question"),questionId:z65.uuid()}).strict(),z65.object({kind:z65.literal("run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z65.object({kind:z65.literal("retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().nullable(),proposalId:z65.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z65.object({kind:z65.literal("merge_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().nullable()}).strict()]),NotificationViewSchema=z65.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema2(NotificationViewSchema),NotificationListSchema=z65.object({items:z65.array(NotificationViewSchema),nextCursor:z65.string().nullable(),unreadCount:z65.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema2(NotificationListSchema),ListNotificationsQuerySchema=z65.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z65.string().min(1).max(120).optional(),sourceKey:z65.string().min(1).max(255).optional(),unread:z65.stringbool().optional(),archived:z65.stringbool().optional(),limit:z65.coerce.number().int().min(1).max(100).optional(),cursor:z65.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z65.object({recipient:NotificationRecipientStateSchema,unreadCount:z65.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema2(NotificationStateSchema),UpdateNotificationStateRequestSchema=z65.object({read:z65.boolean().optional(),archived:z65.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived."),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z65.object({enabled:z65.boolean(),pausedUntil:z65.coerce.date().nullable(),source:z65.enum(["default","explicit"]).optional()})}});import{z as z66}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,QUESTION_DIGEST_PREFERENCE_ENTRY_ID,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z66.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_question","work_review.agent_conflict","schedule.schedule_health","schedule.schedule_compute_allowance","usage.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z66.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z66.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z66.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z66.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z66.object({enabled:z66.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z66.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z66.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z66.enum(["work_review","schedule","usage"]),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z66.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),id:z66.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z66.literal("question_digest"),enabled:z66.boolean(),source:PreferenceSourceSchema,pausedUntil:z66.coerce.date().nullable()}).strict(),z66.object({kind:z66.literal("provider_subscription"),id:z66.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z66.literal("marketing"),name:z66.string(),description:z66.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z66.object({email:EmailNotificationPreferenceSchema,entries:z66.array(NotificationPreferenceEntrySchema),unavailableGroups:z66.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z66.object({enabled:z66.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),enabled:z66.boolean()}).strict(),z66.object({kind:z66.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),enabled:z66.boolean(),pauseDays:z66.number().int().min(1).max(MAX_QUESTION_DIGEST_PAUSE_DAYS).nullable().optional()}).strict().refine(body=>body.enabled||!body.pauseDays,"Pausing requires the toggle to be enabled."),z66.object({kind:z66.literal("provider_subscription"),enabled:z66.boolean()}).strict()])}});import{z as z67}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=z67.object({surface:SurfaceNameSchema,key:z67.string(),label:z67.string()}),InlineSchema=z67.object({text:z67.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z67.discriminatedUnion("type",[z67.object({type:z67.literal("paragraph"),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("preview"),ref:DiffRefSchema,caption:z67.string().optional()}),z67.object({type:z67.literal("code"),code:z67.string(),lang:z67.string().optional(),caption:z67.string().optional()}),z67.object({type:z67.literal("risk"),level:z67.enum(["warning","error"]),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("list"),items:z67.array(z67.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z67.object({headline:z67.string(),blocks:z67.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z67.object({summary:EnvDiffSummarySchema,fingerprint:z67.string(),generatedAt:z67.coerce.date(),cached:z67.boolean().optional(),credits:z67.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z68}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=z68.object({date:z68.string(),visitors:z68.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z68.object({key:z68.string(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z68.object({path:z68.string(),pageName:z68.string().nullable().optional(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z68.object({preset:z68.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z68.string(),requestedTo:z68.string(),effectiveFrom:z68.string(),effectiveTo:z68.string(),isRetentionLimited:z68.boolean(),groupBy:z68.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z68.object({date:z68.string(),content:z68.string(),updatedAt:z68.string(),updatedByUserId:z68.string()}),ProjectPageviewAnalyticsDTOSchema=z68.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative(),bounceRate:z68.number().min(0).max(100),viewsPerVisit:z68.number().nonnegative(),averageVisitDurationSeconds:z68.number().nonnegative(),visitorsSeries:z68.array(ProjectDailyVisitorsDTOSchema),topPages:z68.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z68.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z69}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_common2();init_create_dto();ProjectInviteDTOSchema=z69.object({id:z69.string(),email:z69.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z69.coerce.date(),createdAt:z69.coerce.date(),inviterUserId:z69.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z69.object({id:z69.string(),token:z69.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z69.object({success:z69.boolean(),projectId:z69.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z70}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=z70.object({id:z70.string(),name:z70.string(),image:z70.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z70.object({count:z70.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z70.object({counts:z70.object({signed_up:z70.int(),activated:z70.int()}),credits:z70.object({total:z70.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z70.email(),emailVerified:z70.boolean(),createdAt:z70.coerce.date(),updatedAt:z70.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z71}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common2();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z71.object({id:z71.string(),principalType:ProjectPrincipalTypeSchema,principalId:z71.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z71.coerce.date(),expiresAt:z71.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z71.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z71.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z71.record(z71.string(),z71.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z71.object({access:z71.array(ProjectAccessItemDTOSchema),invites:z71.array(ProjectInviteDTOSchema),organization:z71.object({name:z71.string().nullable(),logo:z71.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z71.object({success:z71.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z71.object({success:z71.boolean(),projectId:z71.uuid()}))}});import{z as z72}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common2();init_create_dto();PublicationStateDTOSchema=z72.object({publicationStatus:PublicationStatusSchema,appUrl:z72.string().nullable(),lastPublishedAt:z72.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z73}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z73.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z73.object({branch:BranchSchema,revision:z73.string().min(1).max(64).nullable(),generation:z73.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z73.url().nullable()})}});import{z as z74}from"zod";var PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,SandboxPullPhaseSchema,SandboxPullFailureCodeSchema,SandboxPullFailureSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewBridgePackageSchema=z74.object({name:z74.string().min(1),version:z74.string().min(1)}),PreviewBridgeCapabilitySchema=z74.object({integrated:z74.boolean(),packages:z74.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z74.object({url:z74.url(),expiresAt:z74.iso.datetime().nullable(),source:z74.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z74.object({name:z74.string().min(1),locator:z74.string().min(1).optional(),source:z74.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z74.object({kind:z74.literal("dependency_build_scripts_blocked"),packageManager:z74.enum(["pnpm","yarn","bun"]),packages:z74.array(z74.string()),targets:z74.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z74.string(),approvalKey:z74.string(),command:z74.string().optional(),approval:z74.object({id:z74.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z74.object({code:z74.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z74.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z74.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z74.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z74.object({message:z74.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z74.number().int().optional().catch(void 0),logTail:z74.array(z74.string()).optional().catch(void 0),logTailTruncated:z74.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z74.object({approvalId:z74.uuid()}),PreviewInstallPolicyApprovalEventSchema=z74.discriminatedUnion("type",[z74.object({type:z74.literal("progress"),step:z74.enum(["approval","install","restart","readiness"]),message:z74.string()}),z74.object({type:z74.literal("approved")}),z74.object({type:z74.literal("complete")}),z74.object({type:z74.literal("error"),code:z74.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z74.string()})])}});import{z as z75}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common2();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z75.string(),slug:z75.string().nullable(),logo:z75.string().nullable(),metadata:z75.record(z75.string(),z75.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z75.object({id:z75.string(),name:z75.string(),email:z75.email(),image:z75.string().nullable()}),OrganizationMemberDTOSchema=z75.object({id:z75.string(),userId:z75.string(),organizationId:z75.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z75.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z76}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,AutomaticSpendStopDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,OptionalSpendRefusalSchema,CreditPurchasePricingDTOSchema,CreditPurchasePricingDTO,PurchaseCreditsDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,CreditPurchasePricingResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common2();init_create_dto();init_response();CancellationReasonCodeSchema=z76.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z76.object({reason:CancellationReasonCodeSchema,details:z76.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z76.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z76.object({offerVersion:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),renewsOn:z76.string()}),PlanMigrationPreviewDTOSchema=z76.object({currency:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),startsAt:z76.string(),renewsAt:z76.string(),nextRenewalAmount:z76.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z76.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z76.object({id:z76.string(),organizationId:z76.string(),legacySubscriptionId:z76.string(),offeredPlanCode:z76.string(),offeredPlanName:z76.string(),offeredPriceAmount:z76.number(),offeredCurrency:z76.string(),offerVersion:z76.string(),state:PlanMigrationStateSchema,checkoutToken:z76.string().nullable(),deadlineAt:z76.string(),transitions:z76.array(z76.object({event:z76.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z76.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z76.object({included:z76.number().optional(),unitPrice:z76.number().optional(),dailyCap:z76.number().nullable().optional()}),EntitlementsDTOSchema=z76.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z76.object({retentionDays:z76.number().int().positive(),canUseExtendedDateRanges:z76.boolean()}).optional(),history:z76.object({retentionDays:z76.number().int().positive()}).optional(),members:z76.object({canInvite:z76.boolean(),maxMembers:z76.number().int().positive().nullable()}).optional(),projects:z76.object({maxProjects:z76.number().int().positive().nullable()}).optional(),domains:z76.object({canUseCustomDomains:z76.boolean(),maxDomains:z76.number().int().nonnegative().nullable()}).optional(),media_storage:z76.object({limitBytes:z76.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z76.object({usedBytes:z76.number().int().nonnegative().nullable(),limitBytes:z76.number().int().nonnegative().nullable(),state:z76.enum(["ready","unavailable"]),measuredAt:z76.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z76.object({toPlanCode:TemplateCodeSchema,effectiveAt:z76.string(),scheduledAt:z76.string().nullable()}),AutomaticSpendStopDTOSchema=z76.object({fromPlanCode:TemplateCodeSchema,cutoffAt:z76.string(),spendStopped:z76.boolean(),settlementEndsAt:z76.string()}),HostingOverageStatusDTOSchema=z76.object({state:z76.enum(["ready","unavailable"]),planCode:z76.string(),overageAvailable:z76.boolean(),overageEnabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().nullable(),periodStart:z76.iso.datetime().nullable(),periodEnd:z76.iso.datetime().nullable(),usedBytes:z76.number().nonnegative().nullable(),includedBytes:z76.number().nonnegative().nullable(),overageBytes:z76.number().nonnegative(),currentOverageAmountMicros:z76.number().nonnegative().nullable(),currency:z76.string().nullable(),status:z76.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z76.object({enabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling overages requires a monthly cap"}),SubscriptionDTOSchema=z76.object({id:z76.string(),external_id:z76.string(),customerId:z76.string(),planId:z76.string(),planCode:z76.union([TemplateCodeSchema,z76.literal("Unknown")]),currentPeriod:z76.object({start:z76.string(),end:z76.string().nullable()}),cancelAt:z76.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z76.string(),nextPaymentAt:z76.string().nullable(),baseAmount:z76.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z76.object({totalCap:z76.number(),dailyCap:z76.number(),usedTotal:z76.number()}),CreditBalanceDTOSchema=z76.object({total:z76.number(),base:z76.number(),dailyBase:z76.number(),purchases:z76.number(),awards:z76.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z76.object({total:z76.number(),nearLimit:z76.boolean(),canChat:z76.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z76.object({dailyFreeAvailable:z76.number(),monthlyAvailable:z76.number(),purchasedAvailable:z76.number(),awardedAvailable:z76.number()}),ProjectDailyCreditAllowanceDTOSchema=z76.object({periodCap:z76.number(),dailyGrant:z76.number(),usedThisPeriod:z76.number(),remainingThisPeriod:z76.number()}),ProjectCreditBalanceDTOSchema=z76.object({projectId:z76.uuid(),organizationId:z76.string(),balance:z76.object({totalAvailable:z76.number(),nearLimit:z76.boolean(),canUseAi:z76.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z76.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z76.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z76.object({planCode:z76.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z76.object({source:z76.enum(["cached_subscription","free_fallback"]),settledMs:z76.number().int().nonnegative(),activeMs:z76.number().int().nonnegative(),reservedMs:z76.number().int().nonnegative().optional(),includedMs:z76.number().int().positive(),remainingMs:z76.number().int().nonnegative(),resetsAt:z76.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().nonnegative(),refillAmountUsd:z76.number().nonnegative()}),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().nonnegative().nullable(),refillAmountUsd:z76.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().min(.01).multipleOf(.01),refillAmountUsd:z76.number().min(.01).multipleOf(.01),expectedRateToken:z76.string().trim().min(1).max(40)}).strict(),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().min(.01).multipleOf(.01),expectedRateToken:z76.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z76.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z76.object({planCode:z76.union([TemplateCodeSchema,z76.literal("Unknown")]).nullable(),canPurchase:z76.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z76.number().int().positive(),minAmountUsd:z76.number().positive(),maxAmountUsd:z76.number().positive(),rateToken:z76.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z76.object({amountUsd:z76.number(),idempotencyKey:z76.string().trim().min(8).max(120),expectedRateToken:z76.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z76.object({invoiceId:z76.string(),newBalance:z76.int(),creditCount:z76.int(),amountUsd:z76.number(),creditsPerDollar:z76.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z76.object({url:z76.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema2(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema2(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema2(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema2(AutoRefillConfigDTOSchema),CreditPurchasePricingResponseSchema=createResponseSchema2(CreditPurchasePricingDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema2(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema2(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema2(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema2(PortalDTOSchema)}});import{z as z77}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=z77.object({brand:z77.string(),last4:z77.string(),exp:z77.string(),isDefault:z77.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z78}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema2,EntryDTO,PaginatedEntriesDTOSchema2,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema2,EntryListResponseSchema,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema2,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema2,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema2,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common2();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z78.string().superRefine((path51,ctx)=>{let segments=path51.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=z78.object({type:z78.literal("renameField"),contentType:z78.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z78.object({enabled:z78.boolean()}).strict(),ContentFieldGroupSchema=z78.object({id:z78.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z78.string().min(1).max(255),default:z78.boolean().optional()}).strict(),ContentTypeDTOSchema=z78.object({id:z78.string(),name:z78.string(),label:z78.string(),isSingleton:z78.boolean(),i18n:ContentTypeI18nSchema,groups:z78.array(ContentFieldGroupSchema).default([]),fields:z78.record(z78.string(),FieldDefinitionSchema),createdAt:z78.string(),updatedAt:z78.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z78.object({contentTypes:z78.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z78.object({id:z78.string(),entryId:z78.string(),documentId:z78.string(),slug:z78.string(),locale:z78.string().optional(),createdAt:z78.string(),updatedAt:z78.string(),__fimo:z78.object({contentType:z78.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({limit:z78.number(),offset:z78.number(),total:z78.number(),hasMore:z78.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z78.object({contentType:z78.string(),count:z78.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z78.object({counts:z78.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z78.object({count:z78.number().int().nonnegative(),sourceLocale:z78.string(),targetLocale:z78.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z78.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z78.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z78.union([z78.string(),z78.number(),z78.boolean(),z78.null()]),entryWhereOperatorSchema2=z78.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z78.array(entryWhereScalarSchema2).optional(),$nin:z78.array(entryWhereScalarSchema2).optional(),$contains:z78.string().optional(),$startsWith:z78.string().optional(),$null:z78.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z78.object({data:z78.record(z78.string(),z78.unknown()),locale:z78.string().min(1).optional(),documentId:z78.uuid().optional()}),entryIdsSchema=z78.array(z78.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z78.object({sql:z78.string().min(1)}),BulkCreateEntriesRequestSchema=z78.object({entries:z78.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z78.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z78.object({updates:z78.array(z78.object({id:z78.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,locale:z78.string().min(1).optional()}),z78.object({where:EntryWhereSchema2,locale:z78.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z78.object({data:z78.array(z78.record(z78.string(),z78.unknown())),meta:z78.object({rowCount:z78.number().int().nonnegative(),truncated:z78.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({created:z78.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({updated:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({deleted:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z79}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z79.object({index:z79.number().int().nonnegative(),contentType:z79.string(),field:z79.string(),value:z79.string(),against:z79.enum(["stored","batch"]),ownerDocumentId:z79.uuid().optional(),ownerIndex:z79.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z79.object({code:z79.literal("unique_conflict"),message:z79.string(),conflicts:z79.array(UniqueConflictSchema),truncated:z79.boolean().optional()})}});import{z as z80}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=z80.object({kind:z80.literal("unique_conflict"),contentType:z80.string(),field:z80.string(),value:z80.string(),documentCount:z80.number().int().positive(),documentIds:z80.array(z80.uuid()),documentIdsTruncated:z80.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z80.object({code:z80.literal("schema_transition_rejected"),message:z80.string(),issues:z80.array(SchemaTransitionIssueSchema),truncated:z80.boolean().optional()})}});import{z as z81}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_common2();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z81.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z81.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z81.object({field:CmsFieldNameSchema,direction:z81.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z81.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z81.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z81.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z81.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z81.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z82}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z82.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z83}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z83.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z83.object({event:ClientTrackedEventSchema,properties:z83.record(z83.string(),z83.unknown()).default({})})}});import{z as z84}from"zod";var AssetPathItemSchema,AssetDTOSchema2,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema2,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common2();init_create_dto();init_response();AssetPathItemSchema=z84.object({id:z84.string(),name:z84.string()}),AssetDTOSchema2=z84.object({id:z84.string(),name:z84.string(),type:AssetTypeSchema,originalFileName:z84.string().nullable(),parentId:z84.string().nullable(),mimeType:z84.string().nullable(),fileSize:z84.number().nullable(),url:z84.string().nullable(),storageKey:z84.string().nullable(),createdAt:z84.string(),updatedAt:z84.string(),altText:z84.string().nullable().optional(),caption:z84.string().nullable().optional(),aiCaption:z84.string().nullable().optional(),aiAltText:z84.string().nullable().optional(),aiTags:z84.array(z84.string()).nullable().optional(),aiPrimaryColor:z84.string().nullable().optional(),aiProcessingStatus:z84.string().nullable().optional(),width:z84.number().nullable().optional(),height:z84.number().nullable().optional(),path:z84.array(AssetPathItemSchema).optional(),hasChildren:z84.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z84.lazy(()=>z84.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z84.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z84.object({error:z84.string(),code:z84.literal("media_storage_limit_exceeded"),usedBytes:z84.number().int().nonnegative(),limitBytes:z84.number().int().positive(),incomingBytes:z84.number().int().nonnegative()}),AssetReferenceScopeSchema=z84.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z84.object({assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z84.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z84.object({totalFiles:z84.number().int().nonnegative(),checkedFiles:z84.number().int().nonnegative(),limit:z84.number().int().positive()}),AssetReferenceFindingDTOSchema=z84.object({assetId:z84.uuid(),entryId:z84.string(),documentId:z84.string(),contentType:z84.string(),locale:z84.string().nullable(),slug:z84.string(),fieldPath:z84.string()}),AssetReferenceScopeResultDTOSchema=z84.object({scope:AssetReferenceScopeSchema,label:z84.string(),state:z84.enum(["available","not-published","failed"]),coverage:z84.enum(["complete","partial","failed"]),referenceCount:z84.number().int().nonnegative().optional(),codeReferenceCount:z84.number().int().nonnegative().optional(),referencedAssetIds:z84.array(z84.uuid()).optional(),references:z84.array(AssetReferenceFindingDTOSchema),reason:z84.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z84.discriminatedUnion("type",[z84.object({type:z84.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z84.object({type:z84.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z84.object({type:z84.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z84.object({replacementAssetId:z84.uuid()}),AssetReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),entriesChanged:z84.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),filesChanged:z84.number().int().nonnegative(),commitSha:z84.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z84.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z84.object({error:z84.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z84.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z84.object({intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z84.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z84.object({id:z84.uuid(),intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()),replacementAssetId:z84.uuid().nullable(),expiresAt:z84.iso.datetime(),undoable:z84.boolean(),requestedByMe:z84.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z84.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z84.object({error:z84.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z85}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z85.object({key:z85.string(),value:z85.string().optional(),defaultValue:z85.string(),locale:z85.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z86}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=z86.object({id:z86.string(),name:z86.string(),type:z86.enum(["file","folder"]),path:z86.string(),children:z86.lazy(()=>z86.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z86.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z86.object({path:z86.string(),exists:z86.boolean(),type:z86.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z87}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema2,FormUpdateSchema2,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z87.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z87.object({minLength:z87.number().optional(),maxLength:z87.number().optional(),min:z87.number().optional(),max:z87.number().optional(),pattern:z87.string().optional(),maxFileSize:z87.number().optional(),accept:z87.array(z87.string()).optional()}),FormFieldSchema=z87.object({type:FormFieldTypeSchema,label:z87.string(),placeholder:z87.string().optional(),required:z87.boolean().optional(),defaultValue:z87.string().optional(),options:z87.array(z87.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z87.record(z87.string(),FormFieldSchema),FormContentSchema2=z87.object({name:z87.string().min(1).max(255),label:z87.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z88}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z88.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z88.object({items:z88.array(ProjectMessagePublicDTOSchema),nextCursor:z88.string().nullable()}),ChatLiveTurnDTOSchema=z88.object({invocationId:z88.string(),step:z88.enum(["preparing","working","compacting","merging"]),startedAt:z88.string()}),ChatLiveTurnStateDTOSchema=z88.object({threadId:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z88.object({id:z88.string(),role:z88.enum(["user","assistant"]),parts:z88.array(z88.unknown()),metadata:z88.record(z88.string(),z88.unknown()).nullable(),versionId:z88.string().nullable().optional(),createdAt:z88.date().transform(value=>value.toISOString()),providerMessageId:z88.string().nullable().optional(),invocationId:z88.string().nullable().optional(),invocationStatus:z88.string().nullable().optional(),invocationTerminalReason:z88.string().nullable().optional()}),ChatAttentionDTOSchema=z88.object({type:z88.literal("merge_conflict"),merge:z88.object({mergeId:z88.string().uuid(),projectId:z88.string(),fromBranch:z88.string(),toBranch:z88.string()}),publishAfterMerge:z88.boolean()}),ChatThreadMessagesPageDTOSchema=z88.object({threadId:z88.string().nullable(),title:z88.string().nullable(),messages:z88.array(ChatThreadMessageDTOSchema),nextCursor:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z88.object({kind:z88.literal("replay"),threadId:z88.string(),userMessageId:z88.string()}),ChatQueuedOutcomeDTOSchema=z88.object({kind:z88.literal("queued"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string()}),ChatBusyOutcomeDTOSchema=z88.object({kind:z88.literal("busy"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string().optional()}),ChatRefusedOutcomeDTOSchema=z88.object({kind:z88.literal("refused"),threadId:z88.string(),userMessageId:z88.string(),refusedInvocationId:z88.string(),terminalReason:z88.string()}),ChatNonStreamingOutcomeDTOSchema=z88.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z88.object({success:z88.boolean(),deletedCount:z88.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema2(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z88.object({code:z88.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z88.string()})}});import{z as z89}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common2();init_create_dto();init_response();UploadResultDTOSchema=z89.object({url:z89.string().url(),key:z89.string(),size:z89.number(),contentType:z89.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z90}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=z90.object({canAccess:z90.boolean(),permissions:z90.record(z90.string(),z90.boolean()),role:z90.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z91}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:z91.string().trim().default(""),sort:z91.enum(["recent","name","relevance"]).default("recent"),category:z91.string().optional()})}});import{z as z92}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_common2();init_create_dto();init_response();DomainStatusSchema=z92.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z92.enum(["fimo","external"]),PaymentStatusSchema=z92.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z92.object({id:z92.string().uuid(),domain:z92.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z92.boolean(),price:z92.number().int().nullable(),renewalPrice:z92.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z92.string().nullable(),failureReason:z92.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z92.object({domain:z92.string(),available:z92.boolean(),premium:z92.boolean(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),purchaseType:z92.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z92.object({domain:z92.string(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),premium:z92.boolean(),allowedYears:z92.array(z92.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z92.object({firstName:z92.string().max(100),lastName:z92.string().max(100),companyName:z92.string().max(100).optional(),address1:z92.string().max(255),address2:z92.string().max(255).optional(),city:z92.string().max(100),state:z92.string().max(100),zip:z92.string().max(20),country:z92.string().max(2),phone:z92.string().max(30),email:z92.union([z92.string().email().max(255),z92.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z92.object({firstName:z92.string().min(1).max(100),lastName:z92.string().min(1).max(100),companyName:z92.string().max(100).optional(),address1:z92.string().min(1).max(255),address2:z92.string().max(255).optional(),city:z92.string().min(1).max(100),state:z92.string().min(1).max(100),zip:z92.string().min(1).max(20),country:z92.string().min(1).max(2),phone:z92.string().min(1).max(30),email:z92.string().email().max(255)}),SearchDomainsRequestSchema=z92.object({keyword:z92.string().min(1).max(100),tldFilter:z92.array(z92.string()).optional()}),CheckAvailabilityRequestSchema=z92.object({domains:z92.array(z92.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=z92.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z92.object({domain:DomainNameSchema,years:z92.number().int().min(1).max(10).optional().default(3),autoRenew:z92.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z92.object({autoRenew:z92.boolean().optional()}),RenewDomainRequestSchema=z92.object({years:z92.number().int().min(1).max(10).optional().default(1),autoRenew:z92.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z92.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z92.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z92.object({verified:z92.boolean(),email:z92.string().nullable(),verifyBy:z92.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z93}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_common2();init_create_dto();init_response();ProjectDomainStatusSchema=z93.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=z93.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=z93.object({txtName:z93.string().nullable().optional(),txtValue:z93.string().nullable().optional(),httpUrl:z93.string().nullable().optional(),httpBody:z93.string().nullable().optional(),cname:z93.string().nullable().optional(),cnameTarget:z93.string().nullable().optional()}),SSLValidationErrorSchema=z93.object({message:z93.string()}),OwnershipVerificationSchema=z93.object({type:z93.string(),name:z93.string(),value:z93.string()}),ProjectDomainSSLDTOSchema=z93.object({status:z93.string(),method:z93.string().nullable(),type:z93.string().nullable(),validationRecords:z93.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z93.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z93.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z93.enum(["subdomain","apex"]),RedirectConfigSchema=z93.object({type:z93.literal("apex_to_www"),linkedDomainId:z93.string()}).nullable().optional(),ProjectDomainDTOSchema=z93.object({id:z93.string(),hostname:z93.string(),status:z93.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z93.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z93.string(),scdCnameTarget:z93.string().optional(),apexTargets:z93.array(z93.string()),dnsAutoConfigured:z93.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z93.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z93.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z93.object({hostname:z93.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:z93.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z93.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z93.object({available:z93.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z93.object({success:z93.boolean(),hostname:z93.string()}))}});import{z as z94}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=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z94.object({available:z94.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z94.object({slug:z94.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z94.object({subdomain:z94.string(),subdomainUpdatedAt:z94.coerce.date()})),SubdomainSuggestionsQuerySchema=z94.object({base:z94.string().max(100).optional(),max:z94.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z94.object({suggestions:z94.array(z94.string())}))}});import{z as z95}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z95.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z95.object({code:ProjectTransferBlockerCodeSchema,message:z95.string(),count:z95.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z95.object({targetOrganizationId:z95.string().min(1)}),ProjectTransferResultDTO=createDTO(z95.object({projectId:z95.string(),sourceOrganizationId:z95.string(),targetOrganizationId:z95.string(),movedThreads:z95.number().int().nonnegative(),revokedInvites:z95.number().int().nonnegative(),revokedGrants:z95.number().int().nonnegative(),preservedGrants:z95.number().int().nonnegative(),warnings:z95.array(z95.string())}))}});import{z as z96}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema2,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema2,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z96.object({translated:z96.number().int().nonnegative(),total:z96.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z96.object({locale:z96.string(),isDefault:z96.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z96.object({defaultLocale:z96.string(),locales:z96.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z96.object({locale:z96.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z96.object({locale:z96.string().min(1).max(40)}),ProjectLocaleMutationSchema=z96.object({locale:z96.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z96.object({locale:z96.string(),entriesDeleted:z96.number().int().nonnegative(),labelsDeleted:z96.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z97}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=z97.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z97.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=z97.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z97.number(),credits:z97.number().optional(),billingMode:z97.enum(["fimo-credits","provider-account"]).optional(),confidence:z97.enum(["exact","estimated","metered"]),basis:z97.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z98}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema2,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=z98.object({options:z98.record(z98.string(),z98.unknown()),name:z98.string().optional(),parentId:z98.string().nullable().optional(),altText:z98.string().optional(),caption:z98.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z98.string().min(1).optional(),model:z98.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=z98.object({jobId:z98.string(),status:z98.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z98.string().nullable().optional(),credits:z98.number().optional(),costUsd:z98.number().optional(),billingMode:z98.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z98.object({error:z98.string(),code:z98.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:z98.array(GenerationTaskIdSchema).optional(),availableModels:z98.array(z98.string()).optional(),issues:z98.array(z98.unknown()).optional()})}});import{z as z99}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=z99.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z99.object({name:z99.string(),key:z99.string(),description:z99.string(),type:FlagTypeSchema,required:z99.boolean(),defaultValue:z99.unknown().optional(),enumValues:z99.array(z99.string()).optional(),isArray:z99.boolean()}),AssetModelPriceSchema=z99.object({unitPrice:z99.number(),unit:z99.string(),confidence:z99.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z99.object({id:z99.string(),shortName:z99.string(),provider:z99.string(),source:z99.string(),modality:z99.enum(["image","video","audio"]),tags:z99.array(z99.string()),displayName:z99.string(),description:z99.string(),flags:z99.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z99.object({model:z99.string(),costUsd:z99.number(),credits:z99.number(),billingMode:z99.enum(["fimo-credits","provider-account"]),confidence:z99.enum(["exact","estimated","metered"]),basis:z99.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z100}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=z100.object({tourId:z100.string(),version:z100.string(),status:z100.string(),completedAt:z100.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z100.array(UserTourDTOSchema))}});import{z as z101}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=z101.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z101.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z101.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z101.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z101.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z101.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z101.enum(["user","agent","system"]),SupportReportTagSchema=z101.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z101.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z101.object({organization:z101.object({id:z101.string().trim().min(1).max(255),name:z101.string().trim().max(240).optional()}),project:z101.object({id:z101.uuid(),name:z101.string().trim().max(240).optional(),createdAt:z101.coerce.date().optional()}).optional(),environment:z101.string().trim().max(255).optional(),clientVersion:z101.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z101.object({message:z101.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z101.string().trim().max(200).optional(),limit:z101.coerce.number().int().min(1).max(100).default(50),offset:z101.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z101.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z101.uuid().nullable().optional(),note:z101.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=z101.object({message:z101.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z101.object({kind:SupportReportLinkKindSchema,label:z101.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z101.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z101.object({kind:SupportReportActorKindSchema,id:z101.string().nullable(),name:z101.string().nullable()}),SupportReportLinkDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportLinkKindSchema,label:z101.string(),url:SupportReportHttpUrlSchema,externalId:z101.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportEventKindSchema,body:z101.string().nullable(),metadata:z101.record(z101.string(),z101.unknown()),actor:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z101.object({id:z101.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z101.array(z101.string()),source:SupportReportSourceSchema,message:z101.string(),reporter:z101.object({id:z101.string().nullable(),name:z101.string().nullable(),email:z101.string().nullable()}),organization:z101.object({id:z101.string().nullable(),name:z101.string()}),project:z101.object({id:z101.uuid().nullable(),name:z101.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z101.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z101.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z101.string().nullable(),deliveredAt:z101.coerce.date().nullable()}).nullable(),duplicateOfReportId:z101.uuid().nullable(),resolvedAt:z101.coerce.date().nullable(),createdAt:z101.coerce.date(),updatedAt:z101.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z101.string().nullable(),clientVersion:z101.string().nullable(),links:z101.array(SupportReportLinkDTOSchema),events:z101.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z101.object({reports:z101.array(SupportReportSummaryDTOSchema),total:z101.number().int().nonnegative(),statusCounts:z101.object({new:z101.number().int().nonnegative(),in_progress:z101.number().int().nonnegative(),waiting:z101.number().int().nonnegative(),resolved:z101.number().int().nonnegative(),duplicate:z101.number().int().nonnegative(),irrelevant:z101.number().int().nonnegative(),ignored:z101.number().int().nonnegative()}),limit:z101.number().int().positive(),offset:z101.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z101.object({id:z101.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z101.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z102}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=z102.iso.datetime({offset:!0}).pipe(z102.coerce.date()),OpsRecentChatInputSchema=z102.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z102.string().trim().min(1).max(255).optional(),limit:z102.coerce.number().int().min(1).max(200).default(100),cursor:z102.string().trim().min(1).max(2e3).optional(),slim:z102.boolean().default(!0),reason:z102.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=z102.object({id:z102.string(),threadId:z102.string(),providerMessageId:z102.string().nullable(),invocationId:z102.string().nullable(),env:z102.string().nullable(),role:z102.string(),parts:z102.array(z102.record(z102.string(),z102.unknown())),metadata:z102.object({status:z102.string().optional(),traceUrl:z102.string().optional(),externalFileChanges:z102.array(z102.unknown()).optional()}),stats:z102.object({toolCount:z102.number().int().nonnegative(),failedToolCount:z102.number().int().nonnegative()}),createdAt:z102.iso.datetime({offset:!0}),project:z102.object({id:z102.string(),name:z102.string(),displayName:z102.string().nullable(),organizationId:z102.string().nullable()})}),OpsRecentChatResponseSchema=z102.object({target:z102.object({backendProfile:OpsBackendProfileSchema,projectEnv:z102.string().nullable()}),window:z102.object({from:z102.iso.datetime({offset:!0}),to:z102.iso.datetime({offset:!0})}),messages:z102.object({items:z102.array(OpsRecentChatMessageSchema),nextCursor:z102.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z103}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z103.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z103.literal(!1),reason:z103.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z104}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z104.object({packageManager:z104.string().trim().min(1).max(200).nullable(),trackedLockfiles:z104.array(z104.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z104.string().trim().min(1)}),OpsProjectPackageManagerSchema=z104.object({target:z104.object({backendProfile:OpsBackendProfileSchema,projectId:z104.uuid(),projectEnv:z104.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z105}from"zod";var OPS_AGENT_BRANCH_DISCARD_LIMIT,OpsAgentBranchAllowlistSchema,OpsAgentBranchRecoveredOwnerSchema,OpsAgentBranchDiscardPlanInputSchema,OpsAgentBranchDiscardApplyInputSchema,OPS_AGENT_BRANCH_DISCARD_BLOCKERS,OpsAgentBranchDiscardBlockerSchema,init_ops_agent_branch_discard_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-branch-discard.dto.js"(){"use strict";init_env();OPS_AGENT_BRANCH_DISCARD_LIMIT=25,OpsAgentBranchAllowlistSchema=z105.array(BranchSchema).min(1,"name at least one Branch to discard").max(OPS_AGENT_BRANCH_DISCARD_LIMIT).refine(branches=>new Set(branches).size===branches.length,{error:"the Branch allowlist must not repeat a Branch"}),OpsAgentBranchRecoveredOwnerSchema=z105.object({branch:BranchSchema,sessionId:z105.uuid()}),OpsAgentBranchDiscardPlanInputSchema=z105.object({branches:OpsAgentBranchAllowlistSchema,reason:z105.string().trim().min(1).max(1e3),recoveredOwners:z105.array(OpsAgentBranchRecoveredOwnerSchema).max(OPS_AGENT_BRANCH_DISCARD_LIMIT).optional()}).refine(input=>(input.recoveredOwners??[]).every(owner=>input.branches.includes(owner.branch)),{error:"every recovered owner must name a Branch from the allowlist",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.branch)).size===owners.length},{error:"recovered owners must not repeat a Branch",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.sessionId)).size===owners.length},{error:"recovered owners must not repeat a session",path:["recoveredOwners"]}),OpsAgentBranchDiscardApplyInputSchema=OpsAgentBranchDiscardPlanInputSchema.safeExtend({planHash:z105.string().trim().length(64)}),OPS_AGENT_BRANCH_DISCARD_BLOCKERS=["branch_not_found","not_agent_session_branch","branch_not_active","production_branch","default_branch","production_source_branch","owner_session_missing","not_project_agent_run","open_merge","live_mcp_session","live_owner","has_descendants","recovery_direct_owner_present","recovery_session_not_found","recovery_session_not_project_agent_run","recovery_session_not_terminal","recovery_session_already_bound"],OpsAgentBranchDiscardBlockerSchema=z105.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z106}from"zod";function createAgentRunWebhookEventDataSchema(status){return z106.object({run:z106.object({id:z106.string(),agentName:z106.string(),trigger:z106.string(),status:z106.literal(status),startedAt:z106.string().nullable(),finishedAt:z106.string().nullable(),reason:z106.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,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_common2();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z106.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z106.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z106.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z106.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z106.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z106.object({reason:WebhookEntryChangeReasonSchema,operationId:z106.string().optional(),batch:z106.object({index:z106.number().int().positive(),total:z106.number().int().positive()}).optional(),changes:z106.array(z106.object({action:WebhookEntryChangeActionSchema,contentType:z106.string(),id:z106.string(),documentId:z106.string(),locale:z106.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z106.object({form:z106.object({id:z106.string(),label:z106.string()}),submission:z106.object({id:z106.string(),data:z106.record(z106.string(),z106.unknown()),submittedAt:z106.string()})}),PublishStartedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("publishing"),startedAt:z106.string()})}),PublishSucceededWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("published"),url:z106.string(),publishedAt:z106.string(),firstPublish:z106.boolean()})}),PublishFailedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("failed"),reason:z106.string()})}),PublishUnpublishedWebhookEventDataSchema=z106.object({publication:z106.object({previousUrl:z106.string(),unpublishedAt:z106.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z106.object({review:z106.object({runId:z106.string(),agentName:z106.string(),reason:z106.string()}),source:z106.object({branch:z106.string(),revision:z106.string(),anchorBranch:z106.string()})}),AgentReviewResolvedWebhookEventDataSchema=z106.object({review:z106.object({id:z106.string(),runId:z106.string(),agentName:z106.string(),resolution:z106.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z106.object({report:z106.object({weekStart:z106.string(),weekEnd:z106.string(),pageviews:z106.number(),visitors:z106.number(),previousPageviews:z106.number(),previousVisitors:z106.number()})}),MediaAssetWebhookEventDataSchema=z106.object({id:z106.string().nullable(),name:z106.string().nullable(),type:z106.string(),mimeType:z106.string().nullable(),fileSize:z106.number().nullable()}),MediaUploadedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("updated")}),MediaDeletedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string()})}),LabelChangedWebhookEventDataSchema=z106.object({changes:z106.array(z106.object({action:z106.enum(["created","updated","deleted"]),key:z106.string(),locale:z106.string(),value:z106.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),isDefault:z106.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),previousCode:z106.string()})}),LocaleDeletedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),entriesDeleted:z106.number().int().nonnegative(),labelsDeleted:z106.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z106.object({merge:z106.object({id:z106.string(),from:BranchSchema,to:BranchSchema,applied:z106.array(z106.object({surface:SurfaceNameSchema,count:z106.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z106.object({branch:z106.object({name:BranchSchema}),version:z106.object({versionId:z106.uuid(),name:z106.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,"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,"branch.restored":BranchRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z106.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z106.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z106.discriminatedUnion("source",[z106.object({source:z106.literal("literal"),value:z106.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z106.object({source:z106.literal("secret"),key:z106.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z106.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z106.object({name:z106.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z106.object({name:z106.string(),source:z106.enum(["literal","secret"]),secretKey:z106.string().nullable(),secretPrefix:z106.string().nullable(),configured:z106.literal(!0)}),WebhookFilterSchema=z106.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z106.string().min(1).max(255).optional(),agentName:z106.string().min(1).max(120).optional(),mediaType:z106.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z106.string().min(1).max(255).optional(),locale:z106.string().min(1).max(120).optional()}),JsonValueSchema=z106.lazy(()=>z106.union([z106.string(),z106.number(),z106.boolean(),z106.null(),z106.array(JsonValueSchema),z106.record(z106.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z106.url(),enabled:z106.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z106.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z106.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z106.url().optional(),enabled:z106.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z106.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z106.boolean().optional()}),TestProjectWebhookRequestSchema=z106.object({eventType:WebhookEventTypeSchema.optional(),data:z106.record(z106.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z106.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z106.uuid(),name:z106.string(),eventType:WebhookEventTypeSchema,enabled:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z106.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z106.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z106.coerce.date().nullable(),deliveryStats24h:z106.object({succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z106.uuid(),projectId:z106.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z106.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z106.number().int().positive(),test:z106.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z106.number().int().nonnegative(),responseStatus:z106.number().int().nullable(),lastErrorCode:z106.string().nullable(),lastErrorMessage:z106.string().nullable(),payloadAvailable:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z106.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z106.string().nullable(),qstashMessageId:z106.string().nullable(),deliveredAt:z106.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z106.object({items:z106.array(WebhookDeliveryDTOSchema),pagination:z106.object({page:z106.number().int().positive(),limit:z106.number().int().positive(),total:z106.number().int().nonnegative(),totalPages:z106.number().int().positive(),hasMore:z106.boolean()}),stats:z106.object({total:z106.number().int().nonnegative(),succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z106.object({id:z106.uuid(),deliveryId:z106.uuid(),attempt:z106.number().int().positive(),status:z106.enum(["delivering","succeeded","failed"]),responseStatus:z106.number().int().nullable(),durationMs:z106.number().int().nonnegative(),responseExcerpt:z106.string().nullable(),errorCode:z106.string().nullable(),errorMessage:z106.string().nullable(),createdAt:z106.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z106.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z106.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z107}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z107.object({key:z107.literal("fimo-2"),enabled:z107.boolean(),dismissed:z107.boolean().default(!1),interacted:z107.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z108}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_common2();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z108.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z108.object({total:z108.number(),base:z108.number(),purchases:z108.number(),awards:z108.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z108.object({id:z108.string(),name:z108.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z108.object({type:z108.string(),brand:z108.string().nullable(),last4:z108.string().nullable(),expirationDate:z108.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z108.object({currency:z108.string(),nextPaymentAmount:z108.number().nullable(),nextPaymentAt:z108.string().nullable(),billingInterval:z108.string().nullable(),totalAmount:z108.number().nullable(),discountAmount:z108.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z108.object({id:z108.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z108.string().nullable(),currentPeriodEndsAt:z108.string().nullable(),renewsAt:z108.string().nullable(),cancelAt:z108.string().nullable(),renewAutomatically:z108.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z108.object({type:z108.enum(["low_balance","critical_balance","approaching_limit"]),message:z108.string(),estimatedPromptsRemaining:z108.number().nullable(),avgCostPerPrompt:z108.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z108.object({monthlyCredits:z108.number().nullable(),usedThisPeriod:z108.number(),remainingThisPeriod:z108.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z108.object({organizationId:z108.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z108.string().nullable(),tenureDays:z108.number().int().nonnegative(),capturedAt:z108.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z108.object({hasSubscription:z108.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z108.number().nullable(),alerts:z108.array(CreditAlertDTOSchema),portalUrl:z108.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z108.object({creditCount:z108.number().int().positive(),expiresAt:z108.string().datetime().nullable().optional(),message:z108.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("free"),amountCents:z108.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("purchase"),amountCents:z108.number().int().positive()}),CreditTopupRequestDTOSchema=z108.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z108.object({success:z108.boolean(),transactionId:z108.string().nullable(),newBalance:z108.number(),creditCount:z108.number(),type:z108.enum(["free","purchase"]),invoiceId:z108.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z109}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=z109.object({totalCredits:z109.number(),totalCostUsd:z109.number(),totalMessages:z109.number(),avgCostPerMessage:z109.number(),periodStart:z109.string().nullable(),periodEnd:z109.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z109.object({date:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z109.array(UsageByUserForProjectDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z109.object({summary:UsageSummaryDTOSchema,byProject:z109.array(UsageByProjectDTOSchema),byUser:z109.array(UsageByUserDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z110}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=z110.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z110.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z110.object({startDate:z110.string().optional(),endDate:z110.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z110.coerce.number().int().positive().default(1),limit:z110.coerce.number().int().positive().max(100).default(20),sortBy:z110.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z110.string().optional(),activeOnly:z110.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z110.object({totalCredits:z110.number(),totalCostUsd:z110.number(),totalMessages:z110.number(),avgCostPerMessage:z110.number(),avgCreditsPerMessage:z110.number(),periodStart:z110.string(),periodEnd:z110.string(),creditsChange:z110.number().nullable(),costChange:z110.number().nullable(),messagesChange:z110.number().nullable(),unattributedCredits:z110.number(),unattributedCostUsd:z110.number(),unattributedMessages:z110.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z110.object({date:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z110.object({organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number(),projectCount:z110.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z110.object({userId:z110.string(),userName:z110.string().nullable(),userEmail:z110.string().nullable(),userImage:z110.string().nullable(),organizationId:z110.string().nullable(),organizationName:z110.string().nullable(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),projectCount:z110.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z110.object({projectId:z110.string(),projectName:z110.string(),projectDisplayName:z110.string().nullable(),organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z110.object({id:z110.string(),name:z110.string(),value:z110.number(),percentage:z110.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z110.object({day:z110.number(),hour:z110.number(),value:z110.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z110.object({summary:UsageOverviewSummaryDTOSchema,timeline:z110.array(UsageTimelinePointDTOSchema),topOrganizations:z110.array(OrganizationUsageRowDTOSchema),topUsers:z110.array(UserUsageRowDTOSchema),topProjects:z110.array(ProjectUsageRowDTOSchema),creditDistribution:z110.array(UsageDistributionItemDTOSchema),userDistribution:z110.array(UsageDistributionItemDTOSchema),heatmap:z110.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z110.object({page:z110.number(),limit:z110.number(),totalItems:z110.number(),totalPages:z110.number(),hasMore:z110.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z110.object({organizations:z110.array(OrganizationUsageRowDTOSchema),top:z110.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z110.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z110.object({users:z110.array(ExtendedUserUsageRowDTOSchema),top:z110.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z110.object({projects:z110.array(ExtendedProjectUsageRowDTOSchema),top:z110.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z110.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z110.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z110.object({credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),createdAt:z110.string(),memberCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z110.object({id:z110.string(),name:z110.string().nullable(),email:z110.string(),image:z110.string().nullable(),createdAt:z110.string(),organizationCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),displayName:z110.string().nullable(),createdAt:z110.string(),organizationId:z110.string(),organizationName:z110.string(),ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z111}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=z111.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z111.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z111.object({command:z111.string().min(1).max(1e4),cwd:z111.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z111.record(z111.string(),z111.string()).optional(),name:z111.string().optional(),waitForCompletion:z111.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z111.object({identifier:z111.string(),status:SandboxProcessStatusSchema,command:z111.string().optional(),startedAt:z111.string().optional(),exitCode:z111.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z111.object({processes:z111.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z111.object({processId:z111.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z111.object({success:z111.boolean(),message:z111.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z112}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common2();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_control_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_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_hosted_preview_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_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_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_transfer_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_branch_discard_dto();init_webhook_dto();init_preview_feature_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(["symbolic-ref","--short","-q","HEAD"],cwd)}async function commitSubjectOrNull(cwd,sha){try{return await runGit(["log","-1","--format=%s",sha,"--"],cwd)}catch{return null}}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 gitErrorSummary(error){let lines=extractStderr(error).split(`
200
+ `).map(line=>line.trim()).filter(line=>line.length>0);return(lines.find(line=>line.startsWith("fatal:")||line.startsWith("error:"))??lines[0]??"git failed").replace(/\/\/[^/\s@]*@/g,"//")}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(commitSubjectOrNull,"commitSubjectOrNull");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(gitErrorSummary,"gitErrorSummary");__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 resolveBranchFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{branch:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||!isValidBranch(branch)?null:{branch,source:"branch"}}catch{return null}}function resolveBranchFromEnvironment(){let branch=process.env.FIMO_ENV?.trim();return branch&&isValidBranch(branch)?branch: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 branch,source,readOnly=!1;if(opts.branchOverride!==void 0){if(!isValidBranch(opts.branchOverride))throw new InvalidBranchOverrideError(opts.branchOverride);branch=opts.branchOverride,source="flag"}else{let fromGit=await resolveBranchFromGit(cwd);if(fromGit)branch=fromGit.branch,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{let fromEnvironment=resolveBranchFromEnvironment();if(!fromEnvironment)throw new GitBranchUndetectedError;branch=fromEnvironment,source="environment"}}if(opts.fimo&&branch!=="prod")try{let{data:branches}=await opts.fimo.execute("branches.list",{projectId:settings.projectId,includeAgentBranches:!0}),names=branches.map(candidate=>candidate.branch);if(!names.includes(branch)&&source==="flag")throw new BranchNotFoundError(branch,names)}catch(err){if(err instanceof BranchNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,branch,source,readOnly:readOnly||void 0}}function branchSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--branch":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"FIMO_ENV",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 Branch: ${ctx.branch} (from ${sourceHint}${ro})`}function branchOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let branch=cur.opts().branch;if(typeof branch=="string"&&branch.length>0)return branch;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let branchOverride2=branchOverrideFromCommand(cmd),cfg=loadConfig(),baseFimo=createCliFimoClient(cfg),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2,fimo:baseFimo});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${branchSourceBanner(ctx)}
200
201
  `)}if(bootstrapOpts.refuseReadOnly&&ctx.readOnly)throw new Error(`Refusing to run a mutating command against read-only Branch '${ctx.branch}'. Switch off the release/* tag or pass --branch <writable-branch>.`);return{ctx,fimo:createCliFimoClient(cfg,ctx.branch)}}var NotInProjectError,InvalidBranchOverrideError,BranchNotFoundError,GitBranchUndetectedError,init_project_context=__esm({"src/cli/utils/project-context.ts"(){init_esm();init_config();init_sdk_transport();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");InvalidBranchOverrideError=class extends Error{static{__name(this,"InvalidBranchOverrideError")}value;constructor(value){super(`--branch value '${value}' is invalid. Branch names must match /^[a-zA-Z0-9._/-]+$/, not start with '-', and be \u2264255 chars.`),this.name="InvalidBranchOverrideError",this.value=value}},BranchNotFoundError=class extends Error{static{__name(this,"BranchNotFoundError")}branch;knownBranches;constructor(branch,knownBranches){super(`Branch '${branch}' not found on the server. Known Branches: ${knownBranches.length>0?knownBranches.join(", "):"(none yet)"}.`),this.name="BranchNotFoundError",this.branch=branch,this.knownBranches=knownBranches}},GitBranchUndetectedError=class extends Error{static{__name(this,"GitBranchUndetectedError")}constructor(){super("Fimo could not detect a current Git Branch. Check out a Branch or pass --branch <name>."),this.name="GitBranchUndetectedError"}};__name(resolveBranchFromGit,"resolveBranchFromGit");__name(resolveBranchFromEnvironment,"resolveBranchFromEnvironment");__name(getProjectContext,"getProjectContext");__name(branchSourceBanner,"branchSourceBanner");__name(branchOverrideFromCommand,"branchOverrideFromCommand");__name(bootstrapProjectCommand,"bootstrapProjectCommand")}});var require_src=__commonJS({"../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2,module2){"use strict";var cursor={to(x,y2){return y2?`\x1B[${y2+1};${x+1}H`:`\x1B[${x+1}G`},move(x,y2){let ret="";return x<0?ret+=`\x1B[${-x}D`:x>0&&(ret+=`\x1B[${x}C`),y2<0?ret+=`\x1B[${-y2}A`:y2>0&&(ret+=`\x1B[${y2}B`),ret},up:__name((count=1)=>`\x1B[${count}A`,"up"),down:__name((count=1)=>`\x1B[${count}B`,"down"),forward:__name((count=1)=>`\x1B[${count}C`,"forward"),backward:__name((count=1)=>`\x1B[${count}D`,"backward"),nextLine:__name((count=1)=>"\x1B[E".repeat(count),"nextLine"),prevLine:__name((count=1)=>"\x1B[F".repeat(count),"prevLine"),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},scroll={up:__name((count=1)=>"\x1B[S".repeat(count),"up"),down:__name((count=1)=>"\x1B[T".repeat(count),"down")},erase={screen:"\x1B[2J",up:__name((count=1)=>"\x1B[1J".repeat(count),"up"),down:__name((count=1)=>"\x1B[J".repeat(count),"down"),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");return count&&(clear+=cursor.left),clear}};module2.exports={cursor,scroll,erase,beep:"\x07"}}});function recoverTenantApiBaseUrl(tenantApiUrl,projectId,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,branch,base)===normalized?base:void 0}catch{return}}function createIdentityService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{getCurrentSession(){return transport.request("/api/auth/get-session")}}}function createGitService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getRemote(projectId,branch){let body=await transport.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-remote`,{},{preserveForbidden:!0});if(!body.data.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(body.data.tenantApiUrl,projectId,branch);if(recovered)return{...body.data,tenantApiBaseUrl:recovered}}return body.data},async getCredential(projectId,branch){return(await transport.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-credential`,{},{preserveForbidden:!0})).data}}}function createPublicationControlService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return{async publish(projectId,request={}){return(await transport.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null},async unpublish(projectId){await transport.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}}}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function transferBlockersFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return[];let blockers=body.blockers;return Array.isArray(blockers)?blockers:[]}function createSandboxService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getHostedPreview(projectId,branch){return(await transport.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment2(branch)}/hosted-preview`)).data},async pull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&&params.set("noRestart","true"),options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),response=await transport.response(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/sandbox/pull${search?`?${search}`:""}`,{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="",failure=null,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
201
202
 
202
203
  `);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
203
204
 
204
205
  `);let eventName="message",dataLines=[];for(let line of rawEvent.split(`
205
206
  `))line.startsWith("event:")?eventName=line.slice(6).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).trim());if(dataLines.length===0)continue;let payload=dataLines.join(`
206
- `);if(eventName==="progress")try{onProgress?.(JSON.parse(payload))}catch{}else if(eventName==="complete"){completed=!0;try{let complete=JSON.parse(payload);readiness=complete.readiness??null,timings=complete.timings??null}catch{}}else if(eventName==="error"){let parsed;try{parsed=JSON.parse(payload)}catch{parsed=void 0}let result=SandboxPullFailureSchema.safeParse(parsed);failure=result.success?result.data:{message:"Sandbox pull failed"}}}}}finally{reader.releaseLock()}if(failure)throw new SandboxPullError(failure);if(!completed)throw new Error("Sandbox pull stream ended before completion");return{readiness:readiness??{status:"skipped",reason:"not_reported",durationMs:0},timings:timings??{dependencyInstallMs:0,serverStartMs:0,readinessMs:readiness?.durationMs??0,totalSandboxMs:0}}}}}function createSupportService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async submit(input){return(await transport.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}}}function createTelemetryService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async trackProjectEvent(projectId,event,properties={}){await transport.request(`/api/management/projects/${projectId}/track`,{method:"POST",body:JSON.stringify({event,properties})})}}}var SandboxPullError,init_project_services=__esm({"src/cli/services/project-services.ts"(){init_esm();init_config();init_sdk_transport();__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(createIdentityService,"createIdentityService");__name(createGitService,"createGitService");__name(createPublicationControlService,"createPublicationControlService");__name(publicationIdFromError,"publicationIdFromError");__name(transferBlockersFromError,"transferBlockersFromError");SandboxPullError=class extends Error{static{__name(this,"SandboxPullError")}failure;constructor(failure){super(failure.message),this.name="SandboxPullError",this.failure=failure}};__name(createSandboxService,"createSandboxService");__name(createSupportService,"createSupportService");__name(createTelemetryService,"createTelemetryService")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});import path18 from"node:path";function remoteRef(remoteBranch){return`refs/remotes/fimo/${remoteBranch}`}async function remoteHeadOrNull(cwd,remoteBranch){try{return await runGit(["rev-parse","--verify",remoteRef(remoteBranch)],cwd)}catch{return null}}function relationFromCounts(ahead,behind){return ahead===0&&behind===0?"in-sync":ahead>0&&behind===0?"ahead":ahead===0&&behind>0?"behind":"diverged"}async function inspectBranchCheckout(args){args.fetch!==!1&&await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd);let[localBranch,localHead,remoteHead]=await Promise.all([currentBranch(args.cwd),runGit(["rev-parse","HEAD"],args.cwd),remoteHeadOrNull(args.cwd,args.remoteBranch)]);if(!remoteHead)return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead:null,ahead:0,behind:0,relation:"missing-remote"};let counts=await runGit(["rev-list","--left-right","--count",`HEAD...${remoteRef(args.remoteBranch)}`],args.cwd),[ahead=0,behind=0]=counts.split(/\s+/).map(Number);return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead,ahead,behind,relation:relationFromCounts(ahead,behind)}}async function hasPathChanges(cwd,filePath){let relativePath=path18.relative(cwd,filePath);return(await runGit(["status","--porcelain","--",relativePath],cwd)).length>0}function assertLocaleMutationState(state){if(state.localBranch!==state.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`The selected environment uses branch '${state.remoteBranch}', but the checkout is on '${state.localBranch}'.`,`Switch to '${state.remoteBranch}' before changing its locales.`);if(state.relation==="missing-remote")throw new BranchCheckoutError("ENV_REMOTE_MISSING",`The environment branch 'fimo/${state.remoteBranch}' does not exist yet.`,"Deploy the project before changing its locale lifecycle.");if(state.relation==="ahead")throw new BranchCheckoutError("ENV_BRANCH_AHEAD",`The local branch is ${state.ahead} commit${state.ahead===1?"":"s"} ahead of fimo/${state.remoteBranch}.`,"Deploy those commits first, then run the locale command again.");if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local branch and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before changing the environment locales.")}async function planLocaleMutationCheckout(args){let state=await inspectBranchCheckout(args);if(assertLocaleMutationState(state),await hasPathChanges(args.cwd,args.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config has uncommitted changes.","Commit, discard, or deploy the config change before changing locales.");if(state.relation==="behind"&&await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes, then run the locale command again.");return{cwd:args.cwd,configPath:args.configPath,state}}async function applyLocaleMutationCheckoutPlan(plan){let current=await inspectBranchCheckout({cwd:plan.cwd,remoteBranch:plan.state.remoteBranch,fetch:!1});if(current.localBranch!==plan.state.localBranch||current.localHead!==plan.state.localHead||current.remoteHead!==plan.state.remoteHead)throw new BranchCheckoutError("ENV_CHECKOUT_CHANGED","The checkout changed after the locale operation was reviewed.","Review the current Git state and run the locale command again.");if(assertLocaleMutationState(current),await hasPathChanges(plan.cwd,plan.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config changed after the locale operation was reviewed.","Commit, discard, or deploy the config change, then run the locale command again.");if(current.relation==="behind"){if(await hasUncommittedChanges(plan.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${current.remoteBranch} and now has uncommitted changes.`,"Stash the changes, then run the locale command again.");await runGit(["merge","--ff-only",remoteRef(current.remoteBranch)],plan.cwd)}}function recoveryCommands(remoteBranch,localBranch,relation){let inspect=`git log --oneline --left-right HEAD...fimo/${remoteBranch}`;return[...localBranch&&localBranch!==remoteBranch?[`git switch ${remoteBranch}`]:[],"git status","git fetch fimo",...relation==="ahead"||relation==="diverged"?[inspect]:[`git merge --ff-only fimo/${remoteBranch}`]]}async function synchronizeLocaleMutationCheckout(args){let state;try{state=await inspectBranchCheckout(args)}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(args.remoteBranch)}}if(state.localBranch!==state.remoteBranch)return{status:"required",reason:`The checkout moved to '${state.localBranch}' after the remote locale change.`,recovery:recoveryCommands(state.remoteBranch,state.localBranch,state.relation)};if(state.relation==="in-sync")return{status:"synchronized"};if(state.relation!=="behind")return{status:"required",reason:`The local branch is ${state.relation} relative to fimo/${state.remoteBranch}.`,recovery:recoveryCommands(state.remoteBranch,void 0,state.relation)};try{return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),{status:"synchronized"}}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(state.remoteBranch)}}}async function prepareDeployCheckout(args){let localBranch=await currentBranch(args.cwd);if(localBranch!==args.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`Deploy requires branch '${args.remoteBranch}'; checkout is on '${localBranch}'.`,`Run 'fimo checkout ${args.remoteBranch}'.`);let state=await inspectBranchCheckout(args);if(state.relation==="missing-remote")return"missing-remote";if(state.relation==="in-sync"||state.relation==="ahead")return"ready";if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before deploying.");if(await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes before deploying.");return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),"ready"}var BranchCheckoutError,init_branch_checkout=__esm({"src/cli/utils/branch-checkout.ts"(){init_git();BranchCheckoutError=class extends Error{constructor(code2,message,hint){super(message);this.code=code2;this.hint=hint;this.name="BranchCheckoutError"}static{__name(this,"BranchCheckoutError")}};__name(remoteRef,"remoteRef");__name(remoteHeadOrNull,"remoteHeadOrNull");__name(relationFromCounts,"relationFromCounts");__name(inspectBranchCheckout,"inspectBranchCheckout");__name(hasPathChanges,"hasPathChanges");__name(assertLocaleMutationState,"assertLocaleMutationState");__name(planLocaleMutationCheckout,"planLocaleMutationCheckout");__name(applyLocaleMutationCheckoutPlan,"applyLocaleMutationCheckoutPlan");__name(recoveryCommands,"recoveryCommands");__name(synchronizeLocaleMutationCheckout,"synchronizeLocaleMutationCheckout");__name(prepareDeployCheckout,"prepareDeployCheckout")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject2(subject){return typeof subject=="object"&&subject!==null}__name(isObject2,"isObject");function toArray(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray,"toArray");function extend(target,source){var index,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key];return target}__name(extend,"extend");function repeat(string,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string;return result}__name(repeat,"repeat");function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject2;module2.exports.toArray=toArray;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
207
+ `);if(eventName==="progress")try{onProgress?.(JSON.parse(payload))}catch{}else if(eventName==="complete"){completed=!0;try{let complete=JSON.parse(payload);readiness=complete.readiness??null,timings=complete.timings??null}catch{}}else if(eventName==="error"){let parsed;try{parsed=JSON.parse(payload)}catch{parsed=void 0}let result=SandboxPullFailureSchema.safeParse(parsed);failure=result.success?result.data:{message:"Sandbox pull failed"}}}}}finally{reader.releaseLock()}if(failure)throw new SandboxPullError(failure);if(!completed)throw new Error("Sandbox pull stream ended before completion");return{readiness:readiness??{status:"skipped",reason:"not_reported",durationMs:0},timings:timings??{dependencyInstallMs:0,serverStartMs:0,readinessMs:readiness?.durationMs??0,totalSandboxMs:0}}}}}function createSupportService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async submit(input){return(await transport.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}}}function createTelemetryService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async trackProjectEvent(projectId,event,properties={}){await transport.request(`/api/management/projects/${projectId}/track`,{method:"POST",body:JSON.stringify({event,properties})})}}}var SandboxPullError,init_project_services=__esm({"src/cli/services/project-services.ts"(){init_esm();init_config();init_sdk_transport();__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(createIdentityService,"createIdentityService");__name(createGitService,"createGitService");__name(createPublicationControlService,"createPublicationControlService");__name(publicationIdFromError,"publicationIdFromError");__name(transferBlockersFromError,"transferBlockersFromError");SandboxPullError=class extends Error{static{__name(this,"SandboxPullError")}failure;constructor(failure){super(failure.message),this.name="SandboxPullError",this.failure=failure}};__name(createSandboxService,"createSandboxService");__name(createSupportService,"createSupportService");__name(createTelemetryService,"createTelemetryService")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});import path18 from"node:path";function remoteRef(remoteBranch){return`refs/remotes/fimo/${remoteBranch}`}async function remoteHeadOrNull(cwd,remoteBranch){try{return await runGit(["rev-parse","--verify",remoteRef(remoteBranch)],cwd)}catch{return null}}function relationFromCounts(ahead,behind){return ahead===0&&behind===0?"in-sync":ahead>0&&behind===0?"ahead":ahead===0&&behind>0?"behind":"diverged"}async function inspectBranchCheckout(args){args.fetch!==!1&&await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd);let[localBranch,localHead,remoteHead]=await Promise.all([currentBranch(args.cwd),runGit(["rev-parse","HEAD"],args.cwd),remoteHeadOrNull(args.cwd,args.remoteBranch)]);if(!remoteHead)return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead:null,ahead:0,behind:0,relation:"missing-remote"};let counts=await runGit(["rev-list","--left-right","--count",`HEAD...${remoteRef(args.remoteBranch)}`],args.cwd),[ahead=0,behind=0]=counts.split(/\s+/).map(Number);return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead,ahead,behind,relation:relationFromCounts(ahead,behind)}}async function hasPathChanges(cwd,filePath){let relativePath=path18.relative(cwd,filePath);return(await runGit(["status","--porcelain","--",relativePath],cwd)).length>0}function assertLocaleMutationState(state){if(state.localBranch!==state.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`The selected environment uses branch '${state.remoteBranch}', but the checkout is on '${state.localBranch}'.`,`Switch to '${state.remoteBranch}' before changing its locales.`);if(state.relation==="missing-remote")throw new BranchCheckoutError("ENV_REMOTE_MISSING",`The environment branch 'fimo/${state.remoteBranch}' does not exist yet.`,"Deploy the project before changing its locale lifecycle.");if(state.relation==="ahead")throw new BranchCheckoutError("ENV_BRANCH_AHEAD",`The local branch is ${state.ahead} commit${state.ahead===1?"":"s"} ahead of fimo/${state.remoteBranch}.`,"Deploy those commits first, then run the locale command again.");if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local branch and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before changing the environment locales.")}async function planLocaleMutationCheckout(args){let state=await inspectBranchCheckout(args);if(assertLocaleMutationState(state),await hasPathChanges(args.cwd,args.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config has uncommitted changes.","Commit, discard, or deploy the config change before changing locales.");if(state.relation==="behind"&&await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes, then run the locale command again.");return{cwd:args.cwd,configPath:args.configPath,state}}async function applyLocaleMutationCheckoutPlan(plan){let current=await inspectBranchCheckout({cwd:plan.cwd,remoteBranch:plan.state.remoteBranch,fetch:!1});if(current.localBranch!==plan.state.localBranch||current.localHead!==plan.state.localHead||current.remoteHead!==plan.state.remoteHead)throw new BranchCheckoutError("ENV_CHECKOUT_CHANGED","The checkout changed after the locale operation was reviewed.","Review the current Git state and run the locale command again.");if(assertLocaleMutationState(current),await hasPathChanges(plan.cwd,plan.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config changed after the locale operation was reviewed.","Commit, discard, or deploy the config change, then run the locale command again.");if(current.relation==="behind"){if(await hasUncommittedChanges(plan.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${current.remoteBranch} and now has uncommitted changes.`,"Stash the changes, then run the locale command again.");await runGit(["merge","--ff-only",remoteRef(current.remoteBranch)],plan.cwd)}}function recoveryCommands(remoteBranch,localBranch,relation){let inspect=`git log --oneline --left-right HEAD...fimo/${remoteBranch}`;return[...localBranch&&localBranch!==remoteBranch?[`git switch ${remoteBranch}`]:[],"git status","git fetch fimo",...relation==="ahead"||relation==="diverged"?[inspect]:[`git merge --ff-only fimo/${remoteBranch}`]]}async function synchronizeLocaleMutationCheckout(args){let state;try{state=await inspectBranchCheckout(args)}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(args.remoteBranch)}}if(state.localBranch!==state.remoteBranch)return{status:"required",reason:`The checkout moved to '${state.localBranch}' after the remote locale change.`,recovery:recoveryCommands(state.remoteBranch,state.localBranch,state.relation)};if(state.relation==="in-sync")return{status:"synchronized"};if(state.relation!=="behind")return{status:"required",reason:`The local branch is ${state.relation} relative to fimo/${state.remoteBranch}.`,recovery:recoveryCommands(state.remoteBranch,void 0,state.relation)};try{return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),{status:"synchronized"}}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(state.remoteBranch)}}}async function inspectPublishSource(args){try{await ensureFimoRemote(args.cwd,args.remoteUrl);let localBranch=await currentBranch(args.cwd).catch(()=>null);if(localBranch===null)return{status:"unavailable",reason:"the checkout is on a detached HEAD, not on a branch"};if(localBranch!==args.remoteBranch)return{status:"unavailable",reason:`the checkout is on '${localBranch}', not '${args.remoteBranch}'`};let state=await inspectBranchCheckout(args);return state.remoteHead===null?{status:"unavailable",reason:`the Fimo remote has no '${args.remoteBranch}' branch yet`}:{status:"known",remoteHead:state.remoteHead,unpushed:state.ahead,dirty:await hasUncommittedChanges(args.cwd)}}catch(error){return{status:"unavailable",reason:gitErrorSummary(error)}}}async function prepareDeployCheckout(args){let localBranch=await currentBranch(args.cwd);if(localBranch!==args.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`Deploy requires branch '${args.remoteBranch}'; checkout is on '${localBranch}'.`,`Run 'fimo checkout ${args.remoteBranch}'.`);let state=await inspectBranchCheckout(args);if(state.relation==="missing-remote")return"missing-remote";if(state.relation==="in-sync"||state.relation==="ahead")return"ready";if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before deploying.");if(await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes before deploying.");return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),"ready"}var BranchCheckoutError,init_branch_checkout=__esm({"src/cli/utils/branch-checkout.ts"(){init_git_credential_setup();init_git();BranchCheckoutError=class extends Error{constructor(code2,message,hint){super(message);this.code=code2;this.hint=hint;this.name="BranchCheckoutError"}static{__name(this,"BranchCheckoutError")}};__name(remoteRef,"remoteRef");__name(remoteHeadOrNull,"remoteHeadOrNull");__name(relationFromCounts,"relationFromCounts");__name(inspectBranchCheckout,"inspectBranchCheckout");__name(hasPathChanges,"hasPathChanges");__name(assertLocaleMutationState,"assertLocaleMutationState");__name(planLocaleMutationCheckout,"planLocaleMutationCheckout");__name(applyLocaleMutationCheckoutPlan,"applyLocaleMutationCheckoutPlan");__name(recoveryCommands,"recoveryCommands");__name(synchronizeLocaleMutationCheckout,"synchronizeLocaleMutationCheckout");__name(inspectPublishSource,"inspectPublishSource");__name(prepareDeployCheckout,"prepareDeployCheckout")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject2(subject){return typeof subject=="object"&&subject!==null}__name(isObject2,"isObject");function toArray(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray,"toArray");function extend(target,source){var index,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key];return target}__name(extend,"extend");function repeat(string,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string;return result}__name(repeat,"repeat");function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject2;module2.exports.toArray=toArray;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
207
208
  \x85\u2028\u2029`.indexOf(this.buffer.charAt(start-1))===-1;)if(start-=1,this.position-start>maxLength/2-1){head=" ... ",start+=5;break}for(tail="",end=this.position;end<this.buffer.length&&`\0\r
208
209
  \x85\u2028\u2029`.indexOf(this.buffer.charAt(end))===-1;)if(end+=1,end-this.position>maxLength/2-1){tail=" ... ",end-=5;break}return snippet=this.buffer.slice(start,end),common.repeat(" ",indent)+head+snippet+tail+`
209
210
  `+common.repeat(" ",indent+this.position-start+head.length)+"^"},"getSnippet");Mark.prototype.toString=__name(function(compact){var snippet,where="";return this.name&&(where+='in "'+this.name+'" '),where+="at line "+(this.line+1)+", column "+(this.column+1),compact||(snippet=this.getSnippet(),snippet&&(where+=`:
@@ -579,7 +580,7 @@ return __eta.res;
579
580
  `)}}return returnStr}__name(compileBody,"compileBody");function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}__name(trimWS,"trimWS");var escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function replaceChar(s){return escMap[s]}__name(replaceChar,"replaceChar");function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}__name(XMLEscape,"XMLEscape");var defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val=>String(val),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;function escapeRegExp(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp,"escapeRegExp");function getLineNo(str,index){return str.slice(0,index).split(`
580
581
  `).length}__name(getLineNo,"getLineNo");function parse6(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
581
582
  `).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}__name(parse6,"parse");function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}__name(handleCache,"handleCache");function render(template,data,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data,options)}__name(render,"render");function renderAsync(template,data,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data,options);return Promise.resolve(res)}__name(renderAsync,"renderAsync");function renderString(template,data){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data)}__name(renderString,"renderString");function renderStringAsync(template,data){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data)}__name(renderStringAsync,"renderStringAsync");var Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse6,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};function readFile2(path51){let res="";try{res=fs18.readFileSync(path51,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path51}`):err}return res}__name(readFile2,"readFile");function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path21.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path21.join(views,formattedPath)}else resolvedFilePath=path21.join(path21.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path21.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}__name(resolvePath2,"resolvePath");function dirIsChild(parent,dir){let relative3=path21.relative(parent,dir);return relative3&&!relative3.startsWith("..")&&!path21.isAbsolute(relative3)}__name(dirIsChild,"dirIsChild");var absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}};import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";var HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}__name(assetPath,"assetPath");var FORMS_REL="src/forms";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}__name(getFormFiles,"getFormFiles");function readForm(path51){try{return JSON.parse(readFileSync4(path51,"utf-8"))}catch{return null}}__name(readForm,"readForm");function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, parse${pascal}FormData, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
582
- `)}__name(generateIndexContent,"generateIndexContent");function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}__name(frameworkFormsTarget,"frameworkFormsTarget");function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}__name(hasPackageExport,"hasPackageExport");function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}__name(requiredFormEntries,"requiredFormEntries");function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, then run \`fimo validate\` again. No generated files were changed.`)}__name(assertFrameworkRuntime,"assertFrameworkRuntime");function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo-next"},{suffix:".client.ts",runtimeImport:"fimo-next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo-sveltekit"}]:[]}__name(generatedFormFiles,"generatedFormFiles");function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__name(syncForms,"syncForms");import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z116}from"zod";var SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z116.object({uid:z116.string().min(1),name:z116.string().min(1).optional(),isSingleton:z116.boolean().optional(),i18n:z116.object({enabled:z116.boolean().optional()}).optional(),groups:z116.array(z116.object({id:z116.string().min(1),label:z116.string().min(1),default:z116.boolean().optional()}).strict()).optional(),fields:z116.record(z116.string(),z116.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}__name(getSchemaFiles,"getSchemaFiles");function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}__name(getGeneratedFiles,"getGeneratedFiles");function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}__name(parseVersion,"parseVersion");function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index=0;index<parsed.parts.length;index++)if(parsed.parts[index]!==parsedMinimum.parts[index])return parsed.parts[index]>parsedMinimum.parts[index];return!parsed.prerelease||parsedMinimum.prerelease}__name(isVersionAtLeast,"isVersionAtLeast");function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}__name(packageExportsSubpath,"packageExportsSubpath");function readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}__name(readProjectPackage,"readProjectPackage");function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}__name(resolveProjectRuntime,"resolveProjectRuntime");function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?"fimo-next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"fimo/ui"}__name(contentRuntimeImportFor,"contentRuntimeImportFor");function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}__name(templatePath,"templatePath");function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo-next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo-next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo-sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}__name(templatesForTarget,"templatesForTarget");function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path51 of schemaFiles){let fileUid=basename(path51,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path51)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path51,"utf-8"))}catch(error){errors.push(`${basename(path51)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path51)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path51)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path51)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path51)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path51)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
583
+ `)}__name(generateIndexContent,"generateIndexContent");function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}__name(frameworkFormsTarget,"frameworkFormsTarget");function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}__name(hasPackageExport,"hasPackageExport");function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}__name(requiredFormEntries,"requiredFormEntries");function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, then run \`fimo validate\` again. No generated files were changed.`)}__name(assertFrameworkRuntime,"assertFrameworkRuntime");function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo-next"},{suffix:".client.ts",runtimeImport:"fimo-next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo-sveltekit"}]:[]}__name(generatedFormFiles,"generatedFormFiles");function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__name(syncForms,"syncForms");import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z116}from"zod";var SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z116.object({uid:z116.string().min(1),name:z116.string().min(1).optional(),isSingleton:z116.boolean().optional(),i18n:z116.object({enabled:z116.boolean().optional()}).optional(),groups:z116.array(z116.object({id:z116.string().min(1),label:z116.string().min(1),default:z116.boolean().optional()}).strict()).optional(),fields:z116.record(z116.string(),z116.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}__name(getSchemaFiles,"getSchemaFiles");function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}__name(getGeneratedFiles,"getGeneratedFiles");function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}__name(parseVersion,"parseVersion");function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index=0;index<parsed.parts.length;index++)if(parsed.parts[index]!==parsedMinimum.parts[index])return parsed.parts[index]>parsedMinimum.parts[index];return!parsed.prerelease||parsedMinimum.prerelease}__name(isVersionAtLeast,"isVersionAtLeast");function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}__name(packageExportsSubpath,"packageExportsSubpath");function readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}__name(readProjectPackage,"readProjectPackage");function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesLegacyNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}__name(resolveProjectRuntime,"resolveProjectRuntime");function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-next":"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"fimo/ui"}__name(contentRuntimeImportFor,"contentRuntimeImportFor");function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}__name(templatePath,"templatePath");function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesLegacyNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"||runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:`${runtimeImport}/client`}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo-sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}__name(templatesForTarget,"templatesForTarget");function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path51 of schemaFiles){let fileUid=basename(path51,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path51)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path51,"utf-8"))}catch(error){errors.push(`${basename(path51)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path51)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path51)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path51)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path51)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path51)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
583
584
  - ${errors.join(`
584
585
  - `)}
585
586
  No generated files were changed.`);return schemas3}__name(loadSchemas,"loadSchemas");function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
@@ -654,13 +655,13 @@ ${failure.stderr}`});break}}__name(emitPushFailure,"emitPushFailure");function e
654
655
  `),padding=" ";return[JSON.stringify(first),...rest.map(l=>`${padding}${JSON.stringify(l)}`)].join(`
655
656
  `)}return JSON.stringify(v)}__name(formatValue,"formatValue");function classifyStatus(diff){return diff.parent===null&&diff.child===null?"missing on both":diff.parent===null?"added on source":diff.child===null?"removed on source":diff.parent===diff.child?"unchanged":"changed"}__name(classifyStatus,"classifyStatus");init_esm();init_cross_surface();init_surface();function renderDiff(report,p2,opts={}){let lines=[],arrow=opts.ascii?"->":"\u2192";lines.push(p2.bold(`${report.fromBranch??report.fromEnv} ${arrow} ${report.toBranch??report.toEnv}`)),lines.push("");let surfaceOpts={ascii:opts.ascii,...opts.all?{maxItems:Number.MAX_SAFE_INTEGER}:{}};for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);delta&&(lines.push(renderSurface(delta,p2,surfaceOpts)),lines.push(""))}return!opts.surface&&report.crossSurface&&report.crossSurface.length>0&&(lines.push(renderCrossSurface(report.crossSurface,p2,{ascii:opts.ascii})),lines.push("")),lines.join(`
656
657
  `).replace(/\n+$/,"")}__name(renderDiff,"renderDiff");init_git();init_project_context();init_project();async function diffCommand(a,b,options,cmd){let program2=cmd?.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch),cwd=resolveProjectCwd(options.cwd),fromBranch=a??ctx.branch,toBranch=b??DEFAULT_BRANCH;if(!b)try{let info=await fimo.execute("branches.get",{projectId:ctx.projectId,branch:fromBranch});toBranch=parentBranchOf(info)??DEFAULT_BRANCH}catch{toBranch=DEFAULT_BRANCH}let surface=options.surface?SurfaceNameSchema.parse(options.surface):void 0;if(surface&&options.key){await runDrillIn({fimo,projectId:ctx.projectId,fromBranch,toBranch,surface,key:options.key});return}if(surface==="code"){if(!await isGitRepo(cwd)){ui.error({command:"diff",code:"NOT_A_GIT_REPO",message:"Not a git repository \u2014 cannot diff the code surface locally."});return}try{let patch=await runGit(["diff",`${fromBranch}..${toBranch}`],cwd);ui.result({command:"diff",data:{from:fromBranch,to:toBranch,surface:"code",patch},render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return patch||p2.dim("(no code differences)")},"render")})}catch(err){ui.error({command:"diff",code:"GIT_DIFF_FAILED",message:`git diff failed: ${err.message}`})}return}let portableReport=await fimo.execute("branches.diff",{projectId:ctx.projectId,branch:fromBranch,against:toBranch,surfaces:surface?[surface==="translations"?"labels":surface]:void 0}),report={fromBranch:portableReport.branch,toBranch:portableReport.against,fromEnv:portableReport.branch,toEnv:portableReport.against,generatedAt:portableReport.generatedAt,fingerprint:portableReport.fingerprint,surfaces:portableReport.surfaces.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),crossSurface:portableReport.crossSurface?.map(finding=>({...finding,source:{...finding.source,surface:finding.source.surface==="labels"?"translations":finding.source.surface},target:{...finding.target,surface:finding.target.surface==="labels"?"translations":finding.target.surface}}))};ui.result({command:"diff",data:report,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return renderDiff(report,p2,{surface,all:options.all,ascii:rctx.ascii})},"render")})}__name(diffCommand,"diffCommand");async function runDrillIn(args){let{fimo,projectId,fromBranch,toBranch,surface,key}=args;try{switch(surface){case"code":{let payload=await fimo.execute("branches.diffCodeFile",{projectId,branch:fromBranch,path:key,against:toBranch});ui.result({command:"diff",data:payload,render:__name(rctx=>renderCodeFileDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"content":{let[collection,rowId]=splitOnce(key,":");if(!collection||!rowId)return invalidKey("content","<collection>:<rowId>");let payload=await fimo.execute("branches.diffContentEntry",{projectId,branch:fromBranch,collection,rowId,against:toBranch});ui.result({command:"diff",data:payload,render:__name(rctx=>renderContentRowDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"translations":{let[locale,i18nKey]=splitOnce(key,":");if(!locale||!i18nKey)return invalidKey("translations","<locale>:<i18nKey>");let payload=await fimo.execute("branches.diffLabel",{projectId,branch:fromBranch,locale,key:i18nKey,against:toBranch});ui.result({command:"diff",data:payload,render:__name(rctx=>renderTranslationRowDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"schemas":{let payload=await fimo.execute("branches.diffSchema",{projectId,branch:fromBranch,typeName:key,against:toBranch});ui.result({command:"diff",data:payload,render:__name(rctx=>renderSchemaTypeDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"forms":{let payload=await fimo.execute("branches.diffForm",{projectId,branch:fromBranch,formName:key,against:toBranch});ui.result({command:"diff",data:payload,render:__name(rctx=>renderFormSchemaDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"assets":{let payload=await fimo.execute("branches.diffAsset",{projectId,branch:fromBranch,assetId:key,against:toBranch});ui.result({command:"diff",data:payload,render:__name(rctx=>renderAssetDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}}}catch(err){let message=err instanceof Error?err.message:String(err);ui.error({command:"diff",code:"DRILL_FETCH_FAILED",message:`Failed to fetch ${surface} ${key}: ${message}`})}}__name(runDrillIn,"runDrillIn");function splitOnce(s,sep2){let idx=s.indexOf(sep2);return idx<0?[s,""]:[s.slice(0,idx),s.slice(idx+1)]}__name(splitOnce,"splitOnce");function invalidKey(surface,expected){ui.error({command:"diff",code:"DRILL_INVALID_KEY",message:`--key for surface '${surface}' must be in the form '${expected}'`})}__name(invalidKey,"invalidKey");init_dist();import process7 from"node:process";import{Buffer as Buffer2}from"node:buffer";import path31 from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";import{promisify as promisify8}from"node:util";import childProcess from"node:child_process";import fs31,{constants as fsConstants2}from"node:fs/promises";import process3 from"node:process";import fs30,{constants as fsConstants}from"node:fs/promises";import process2 from"node:process";import os from"node:os";import fs29 from"node:fs";import fs28 from"node:fs";import fs27 from"node:fs";var isDockerCached;function hasDockerEnv(){try{return fs27.statSync("/.dockerenv"),!0}catch{return!1}}__name(hasDockerEnv,"hasDockerEnv");function hasDockerCGroup(){try{return fs27.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}__name(hasDockerCGroup,"hasDockerCGroup");function isDocker(){return isDockerCached===void 0&&(isDockerCached=hasDockerEnv()||hasDockerCGroup()),isDockerCached}__name(isDocker,"isDocker");var cachedResult,hasContainerEnv=__name(()=>{try{return fs28.statSync("/run/.containerenv"),!0}catch{return!1}},"hasContainerEnv");function isInsideContainer(){return cachedResult===void 0&&(cachedResult=hasContainerEnv()||isDocker()),cachedResult}__name(isInsideContainer,"isInsideContainer");var isWsl=__name(()=>{if(process2.platform!=="linux")return!1;if(os.release().toLowerCase().includes("microsoft"))return!isInsideContainer();try{if(fs29.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!isInsideContainer()}catch{}return fs29.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||fs29.existsSync("/run/WSL")?!isInsideContainer():!1},"isWsl"),is_wsl_default=process2.env.__IS_WSL_TEST__?isWsl:isWsl();var wslDrivesMountPoint=(()=>{let defaultMountPoint="/mnt/",mountPoint;return async function(){if(mountPoint)return mountPoint;let configFilePath="/etc/wsl.conf",isConfigFileExists=!1;try{await fs30.access(configFilePath,fsConstants.F_OK),isConfigFileExists=!0}catch{}if(!isConfigFileExists)return defaultMountPoint;let configContent=await fs30.readFile(configFilePath,{encoding:"utf8"}),configMountPoint=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);return configMountPoint?(mountPoint=configMountPoint.groups.mountPoint.trim(),mountPoint=mountPoint.endsWith("/")?mountPoint:`${mountPoint}/`,mountPoint):defaultMountPoint}})(),powerShellPathFromWsl=__name(async()=>`${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,"powerShellPathFromWsl"),powerShellPath=__name(async()=>is_wsl_default?powerShellPathFromWsl():`${process3.env.SYSTEMROOT||process3.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,"powerShellPath");function defineLazyProperty(object,propertyName,valueGetter){let define=__name(value=>Object.defineProperty(object,propertyName,{value,enumerable:!0,writable:!0}),"define");return Object.defineProperty(object,propertyName,{configurable:!0,enumerable:!0,get(){let result=valueGetter();return define(result),result},set(value){define(value)}}),object}__name(defineLazyProperty,"defineLazyProperty");import{promisify as promisify7}from"node:util";import process6 from"node:process";import{execFile as execFile7}from"node:child_process";import{promisify as promisify4}from"node:util";import process4 from"node:process";import{execFile as execFile4}from"node:child_process";var execFileAsync4=promisify4(execFile4);async function defaultBrowserId(){if(process4.platform!=="darwin")throw new Error("macOS only");let{stdout}=await execFileAsync4("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),browserId=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id??"com.apple.Safari";return browserId==="com.apple.safari"?"com.apple.Safari":browserId}__name(defaultBrowserId,"defaultBrowserId");import process5 from"node:process";import{promisify as promisify5}from"node:util";import{execFile as execFile5,execFileSync as execFileSync2}from"node:child_process";var execFileAsync5=promisify5(execFile5);async function runAppleScript(script,{humanReadableOutput=!0,signal}={}){if(process5.platform!=="darwin")throw new Error("macOS only");let outputArguments=humanReadableOutput?[]:["-ss"],execOptions={};signal&&(execOptions.signal=signal);let{stdout}=await execFileAsync5("osascript",["-e",script,outputArguments],execOptions);return stdout.trim()}__name(runAppleScript,"runAppleScript");async function bundleName(bundleId){return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
657
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}__name(bundleName,"bundleName");import{promisify as promisify6}from"node:util";import{execFile as execFile6}from"node:child_process";var execFileAsync6=promisify6(execFile6),windowsBrowserProgIds={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},_windowsBrowserProgIdMap=new Map(Object.entries(windowsBrowserProgIds)),UnknownBrowserError=class extends Error{static{__name(this,"UnknownBrowserError")}};async function defaultBrowser(_execFileAsync=execFileAsync6){let{stdout}=await _execFileAsync("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),match=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);if(!match)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);let{id}=match.groups,dotIndex=id.lastIndexOf("."),hyphenIndex=id.lastIndexOf("-"),baseIdByDot=dotIndex===-1?void 0:id.slice(0,dotIndex),baseIdByHyphen=hyphenIndex===-1?void 0:id.slice(0,hyphenIndex);return windowsBrowserProgIds[id]??windowsBrowserProgIds[baseIdByDot]??windowsBrowserProgIds[baseIdByHyphen]??{name:id,id}}__name(defaultBrowser,"defaultBrowser");var execFileAsync7=promisify7(execFile7),titleize=__name(string=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,x=>x.toUpperCase()),"titleize");async function defaultBrowser2(){if(process6.platform==="darwin"){let id=await defaultBrowserId();return{name:await bundleName(id),id}}if(process6.platform==="linux"){let{stdout}=await execFileAsync7("xdg-mime",["query","default","x-scheme-handler/http"]),id=stdout.trim();return{name:titleize(id.replace(/.desktop$/,"").replace("-"," ")),id}}if(process6.platform==="win32")return defaultBrowser();throw new Error("Only macOS, Linux, and Windows are supported")}__name(defaultBrowser2,"defaultBrowser");var execFile8=promisify8(childProcess.execFile),__dirname=path31.dirname(fileURLToPath5(import.meta.url)),localXdgOpenPath=path31.join(__dirname,"xdg-open"),{platform,arch}=process7;async function getWindowsDefaultBrowserFromWsl(){let powershellPath=await powerShellPath(),rawCommand=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,encodedCommand=Buffer2.from(rawCommand,"utf16le").toString("base64"),{stdout}=await execFile8(powershellPath,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",encodedCommand],{encoding:"utf8"}),progId=stdout.trim(),browserMap={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return browserMap[progId]?{id:browserMap[progId]}:{}}__name(getWindowsDefaultBrowserFromWsl,"getWindowsDefaultBrowserFromWsl");var pTryEach=__name(async(array,mapper)=>{let latestError;for(let item of array)try{return await mapper(item)}catch(error){latestError=error}throw latestError},"pTryEach"),baseOpen=__name(async options=>{if(options={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options},Array.isArray(options.app))return pTryEach(options.app,singleApp=>baseOpen({...options,app:singleApp}));let{name:app,arguments:appArguments=[]}=options.app??{};if(appArguments=[...appArguments],Array.isArray(app))return pTryEach(app,appName=>baseOpen({...options,app:{name:appName,arguments:appArguments}}));if(app==="browser"||app==="browserPrivate"){let ids={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},flags={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},browser=is_wsl_default?await getWindowsDefaultBrowserFromWsl():await defaultBrowser2();if(browser.id in ids){let browserName=ids[browser.id];return app==="browserPrivate"&&appArguments.push(flags[browserName]),baseOpen({...options,app:{name:apps[browserName],arguments:appArguments}})}throw new Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={};if(platform==="darwin")command="open",options.wait&&cliArguments.push("--wait-apps"),options.background&&cliArguments.push("--background"),options.newInstance&&cliArguments.push("--new"),app&&cliArguments.push("-a",app);else if(platform==="win32"||is_wsl_default&&!isInsideContainer()&&!app){command=await powerShellPath(),cliArguments.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),is_wsl_default||(childProcessOptions.windowsVerbatimArguments=!0);let encodedArguments=["Start"];options.wait&&encodedArguments.push("-Wait"),app?(encodedArguments.push(`"\`"${app}\`""`),options.target&&appArguments.push(options.target)):options.target&&encodedArguments.push(`"${options.target}"`),appArguments.length>0&&(appArguments=appArguments.map(argument=>`"\`"${argument}\`""`),encodedArguments.push("-ArgumentList",appArguments.join(","))),options.target=Buffer2.from(encodedArguments.join(" "),"utf16le").toString("base64")}else{if(app)command=app;else{let isBundled=!__dirname||__dirname==="/",exeLocalXdgOpen=!1;try{await fs31.access(localXdgOpenPath,fsConstants2.X_OK),exeLocalXdgOpen=!0}catch{}command=process7.versions.electron??(platform==="android"||isBundled||!exeLocalXdgOpen)?"xdg-open":localXdgOpenPath}appArguments.length>0&&cliArguments.push(...appArguments),options.wait||(childProcessOptions.stdio="ignore",childProcessOptions.detached=!0)}platform==="darwin"&&appArguments.length>0&&cliArguments.push("--args",...appArguments),options.target&&cliArguments.push(options.target);let subprocess=childProcess.spawn(command,cliArguments,childProcessOptions);return options.wait?new Promise((resolve10,reject)=>{subprocess.once("error",reject),subprocess.once("close",exitCode=>{if(!options.allowNonzeroExitCode&&exitCode>0){reject(new Error(`Exited with code ${exitCode}`));return}resolve10(subprocess)})}):(subprocess.unref(),subprocess)},"baseOpen"),open=__name((target,options)=>{if(typeof target!="string")throw new TypeError("Expected a `target`");return baseOpen({...options,target})},"open");function detectArchBinary(binary){if(typeof binary=="string"||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw new Error(`${arch} is not supported`);return archBinary}__name(detectArchBinary,"detectArchBinary");function detectPlatformBinary({[platform]:platformBinary},{wsl}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw new Error(`${platform} is not supported`);return detectArchBinary(platformBinary)}__name(detectPlatformBinary,"detectPlatformBinary");var apps={};defineLazyProperty(apps,"chrome",()=>detectPlatformBinary({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));defineLazyProperty(apps,"brave",()=>detectPlatformBinary({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));defineLazyProperty(apps,"firefox",()=>detectPlatformBinary({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));defineLazyProperty(apps,"edge",()=>detectPlatformBinary({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));defineLazyProperty(apps,"browser",()=>"browser");defineLazyProperty(apps,"browserPrivate",()=>"browserPrivate");var open_default=open;init_config();init_sdk_transport();init_project();function resolveProject(options){if(options.project)return{projectId:options.project};let settings=loadProjectSettings(resolveProjectCwd(options.cwd));return{projectId:settings.projectId,organizationId:settings.organizationId}}__name(resolveProject,"resolveProject");function derivePublicDomain(project,fallback){if(project?.appUrl)try{let parts=new URL(project.appUrl).hostname.split(".");if(parts.length>=2)return parts.slice(1).join(".")}catch{}return fallback}__name(derivePublicDomain,"derivePublicDomain");async function loadPublicDomain(fimo,project){if(project?.appUrl)return derivePublicDomain(project,"fimo.site");try{let features=await fimo.execute("domains.features",{});return derivePublicDomain(project,features.publicationDomain)}catch{return derivePublicDomain(project,"fimo.site")}}__name(loadPublicDomain,"loadPublicDomain");function paywallHint(organizationId){return`Custom domains require a Premium plan. Upgrade at ${organizationId?`https://fimo.ai/billing/${organizationId}`:"https://fimo.ai/billing"}`}__name(paywallHint,"paywallHint");function isPaywall(err){return err instanceof ApiRequestError&&err.status===403}__name(isPaywall,"isPaywall");function updateErrorToMessage(reason){switch(reason){case"invalid_shape":return"Invalid URL. Use lowercase letters, numbers, and hyphens (max 63 chars).";case"reserved":case"taken_by_project":case"taken_by_legacy_custom_domain":return"This URL is not available.";case"hosting_sync_failed":case"kv_sync_failed":return"Couldn't sync the URL. Try again in a moment.";default:return"Failed to update URL."}}__name(updateErrorToMessage,"updateErrorToMessage");function pad(value,width){return value.length>=width?value:value+" ".repeat(width-value.length)}__name(pad,"pad");function statusLabel2(domain){return domain.status==="active"&&domain.ssl.status==="active"?"verified":domain.ssl.status==="failed"||(domain.ssl.validationErrors?.length??0)>0?"failed":"pending"}__name(statusLabel2,"statusLabel");function renderDnsInstructions(domain){if(domain.dnsAutoConfigured)return"DNS auto-configured by Fimo \u2014 nothing to do.";let rows=[];rows.push({type:"CNAME",name:domain.hostname,value:domain.cnameTarget});for(let record of domain.ownershipVerification??[])rows.push({type:record.type??"TXT",name:record.name,value:record.value});for(let record of domain.ssl.validationRecords??[])record.txtName&&record.txtValue?rows.push({type:"TXT",name:record.txtName,value:record.txtValue}):record.cname&&record.cnameTarget&&rows.push({type:"CNAME",name:record.cname,value:record.cnameTarget});let typeW=Math.max(4,...rows.map(r=>r.type.length)),nameW=Math.max(4,...rows.map(r=>r.name.length)),lines=["","DNS records to add at your registrar:",""];lines.push(` ${pad("TYPE",typeW)} ${pad("NAME",nameW)} VALUE`);for(let r of rows)lines.push(` ${pad(r.type,typeW)} ${pad(r.name,nameW)} ${r.value}`);return lines.join(`
658
- `)}__name(renderDnsInstructions,"renderDnsInstructions");function parseWait(opts,defaultEnabled){if(opts.noWait)return{enabled:!1,timeoutMs:0};if(opts.wait===void 0||opts.wait===null)return{enabled:defaultEnabled,timeoutMs:300*1e3};if(opts.wait===!0)return{enabled:!0,timeoutMs:300*1e3};let match=String(opts.wait).trim().toLowerCase().match(/^(\d+)(s|m)?$/);if(!match)return{enabled:!0,timeoutMs:300*1e3};let n=parseInt(match[1],10);return{enabled:!0,timeoutMs:(match[2]??"s")==="m"?n*6e4:n*1e3}}__name(parseWait,"parseWait");async function pollUntilVerified(fimo,projectId,initial,timeoutMs,organizationId){let start=Date.now(),sp=spinner(`Waiting for ${initial.hostname} (SSL: ${initial.ssl.status})`),current=initial;for(;Date.now()-start<timeoutMs;){if(current.status==="active"&&current.ssl.status==="active")return sp.succeed(`Verified \u2014 ${current.hostname} is live with SSL.`),current;if(current.ssl.status==="failed"||(current.ssl.validationErrors?.length??0)>0)return sp.fail(`SSL validation failed for ${current.hostname}.`),current;await new Promise(resolve10=>setTimeout(resolve10,5e3));try{current=await fimo.execute("domains.refresh",{projectId,domainId:initial.id}),sp.update(`Waiting for ${current.hostname} (SSL: ${current.ssl.status})`)}catch(err){return rethrowCliAuthError(err,()=>sp.fail("Authentication required")),isPaywall(err)?(sp.fail(paywallHint(organizationId)),current):(sp.fail(`Refresh failed: ${err instanceof Error?err.message:String(err)}`),current)}}return sp.fail(`Timed out after ${Math.round(timeoutMs/1e3)}s waiting for ${initial.hostname}.`),current}__name(pollUntilVerified,"pollUntilVerified");async function findDomainByIdOrHostname(fimo,projectId,needle){let domains2=await fimo.execute("domains.list",{projectId}),lower=needle.toLowerCase();return domains2.find(d3=>d3.id===needle||d3.hostname.toLowerCase()===lower)??null}__name(findDomainByIdOrHostname,"findDomainByIdOrHostname");async function domainsListCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId,organizationId}=resolveProject(options),project=(await fimo.execute("projects.get",{projectId})).data,publicDomain=await loadPublicDomain(fimo,project),domains2=[],domainsBlocked=!1;try{domains2=await fimo.execute("domains.list",{projectId})}catch(err){if(rethrowCliAuthError(err),isPaywall(err))domainsBlocked=!0;else throw err}let subdomain=project.subdomain??project.name,data={defaultUrl:{subdomain,url:`${subdomain}.${publicDomain}`},customDomains:domains2,customDomainsBlocked:domainsBlocked};ui.result({command:"domains list",data,render:__name(()=>{let lines=[];if(lines.push("Default URL"),lines.push(` ${subdomain}.${publicDomain}`),lines.push(""),lines.push("Custom domains"),domainsBlocked)return lines.push(` (${paywallHint(organizationId??project.organizationId??void 0)})`),lines.join(`
658
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}__name(bundleName,"bundleName");import{promisify as promisify6}from"node:util";import{execFile as execFile6}from"node:child_process";var execFileAsync6=promisify6(execFile6),windowsBrowserProgIds={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},_windowsBrowserProgIdMap=new Map(Object.entries(windowsBrowserProgIds)),UnknownBrowserError=class extends Error{static{__name(this,"UnknownBrowserError")}};async function defaultBrowser(_execFileAsync=execFileAsync6){let{stdout}=await _execFileAsync("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),match=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);if(!match)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);let{id}=match.groups,dotIndex=id.lastIndexOf("."),hyphenIndex=id.lastIndexOf("-"),baseIdByDot=dotIndex===-1?void 0:id.slice(0,dotIndex),baseIdByHyphen=hyphenIndex===-1?void 0:id.slice(0,hyphenIndex);return windowsBrowserProgIds[id]??windowsBrowserProgIds[baseIdByDot]??windowsBrowserProgIds[baseIdByHyphen]??{name:id,id}}__name(defaultBrowser,"defaultBrowser");var execFileAsync7=promisify7(execFile7),titleize=__name(string=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,x=>x.toUpperCase()),"titleize");async function defaultBrowser2(){if(process6.platform==="darwin"){let id=await defaultBrowserId();return{name:await bundleName(id),id}}if(process6.platform==="linux"){let{stdout}=await execFileAsync7("xdg-mime",["query","default","x-scheme-handler/http"]),id=stdout.trim();return{name:titleize(id.replace(/.desktop$/,"").replace("-"," ")),id}}if(process6.platform==="win32")return defaultBrowser();throw new Error("Only macOS, Linux, and Windows are supported")}__name(defaultBrowser2,"defaultBrowser");var execFile8=promisify8(childProcess.execFile),__dirname=path31.dirname(fileURLToPath5(import.meta.url)),localXdgOpenPath=path31.join(__dirname,"xdg-open"),{platform,arch}=process7;async function getWindowsDefaultBrowserFromWsl(){let powershellPath=await powerShellPath(),rawCommand=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,encodedCommand=Buffer2.from(rawCommand,"utf16le").toString("base64"),{stdout}=await execFile8(powershellPath,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",encodedCommand],{encoding:"utf8"}),progId=stdout.trim(),browserMap={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return browserMap[progId]?{id:browserMap[progId]}:{}}__name(getWindowsDefaultBrowserFromWsl,"getWindowsDefaultBrowserFromWsl");var pTryEach=__name(async(array,mapper)=>{let latestError;for(let item of array)try{return await mapper(item)}catch(error){latestError=error}throw latestError},"pTryEach"),baseOpen=__name(async options=>{if(options={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options},Array.isArray(options.app))return pTryEach(options.app,singleApp=>baseOpen({...options,app:singleApp}));let{name:app,arguments:appArguments=[]}=options.app??{};if(appArguments=[...appArguments],Array.isArray(app))return pTryEach(app,appName=>baseOpen({...options,app:{name:appName,arguments:appArguments}}));if(app==="browser"||app==="browserPrivate"){let ids={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},flags={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},browser=is_wsl_default?await getWindowsDefaultBrowserFromWsl():await defaultBrowser2();if(browser.id in ids){let browserName=ids[browser.id];return app==="browserPrivate"&&appArguments.push(flags[browserName]),baseOpen({...options,app:{name:apps[browserName],arguments:appArguments}})}throw new Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={};if(platform==="darwin")command="open",options.wait&&cliArguments.push("--wait-apps"),options.background&&cliArguments.push("--background"),options.newInstance&&cliArguments.push("--new"),app&&cliArguments.push("-a",app);else if(platform==="win32"||is_wsl_default&&!isInsideContainer()&&!app){command=await powerShellPath(),cliArguments.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),is_wsl_default||(childProcessOptions.windowsVerbatimArguments=!0);let encodedArguments=["Start"];options.wait&&encodedArguments.push("-Wait"),app?(encodedArguments.push(`"\`"${app}\`""`),options.target&&appArguments.push(options.target)):options.target&&encodedArguments.push(`"${options.target}"`),appArguments.length>0&&(appArguments=appArguments.map(argument=>`"\`"${argument}\`""`),encodedArguments.push("-ArgumentList",appArguments.join(","))),options.target=Buffer2.from(encodedArguments.join(" "),"utf16le").toString("base64")}else{if(app)command=app;else{let isBundled=!__dirname||__dirname==="/",exeLocalXdgOpen=!1;try{await fs31.access(localXdgOpenPath,fsConstants2.X_OK),exeLocalXdgOpen=!0}catch{}command=process7.versions.electron??(platform==="android"||isBundled||!exeLocalXdgOpen)?"xdg-open":localXdgOpenPath}appArguments.length>0&&cliArguments.push(...appArguments),options.wait||(childProcessOptions.stdio="ignore",childProcessOptions.detached=!0)}platform==="darwin"&&appArguments.length>0&&cliArguments.push("--args",...appArguments),options.target&&cliArguments.push(options.target);let subprocess=childProcess.spawn(command,cliArguments,childProcessOptions);return options.wait?new Promise((resolve10,reject)=>{subprocess.once("error",reject),subprocess.once("close",exitCode=>{if(!options.allowNonzeroExitCode&&exitCode>0){reject(new Error(`Exited with code ${exitCode}`));return}resolve10(subprocess)})}):(subprocess.unref(),subprocess)},"baseOpen"),open=__name((target,options)=>{if(typeof target!="string")throw new TypeError("Expected a `target`");return baseOpen({...options,target})},"open");function detectArchBinary(binary){if(typeof binary=="string"||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw new Error(`${arch} is not supported`);return archBinary}__name(detectArchBinary,"detectArchBinary");function detectPlatformBinary({[platform]:platformBinary},{wsl}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw new Error(`${platform} is not supported`);return detectArchBinary(platformBinary)}__name(detectPlatformBinary,"detectPlatformBinary");var apps={};defineLazyProperty(apps,"chrome",()=>detectPlatformBinary({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));defineLazyProperty(apps,"brave",()=>detectPlatformBinary({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));defineLazyProperty(apps,"firefox",()=>detectPlatformBinary({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));defineLazyProperty(apps,"edge",()=>detectPlatformBinary({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));defineLazyProperty(apps,"browser",()=>"browser");defineLazyProperty(apps,"browserPrivate",()=>"browserPrivate");var open_default=open;init_config();init_sdk_transport();init_project();function resolveProject(options){return options.project?{projectId:options.project}:{projectId:loadProjectSettings(resolveProjectCwd(options.cwd)).projectId}}__name(resolveProject,"resolveProject");function derivePublicDomain(project,fallback){if(project?.appUrl)try{let parts=new URL(project.appUrl).hostname.split(".");if(parts.length>=2)return parts.slice(1).join(".")}catch{}return fallback}__name(derivePublicDomain,"derivePublicDomain");async function loadPublicDomain(fimo,project){if(project?.appUrl)return derivePublicDomain(project,"fimo.site");try{let features=await fimo.execute("domains.features",{});return derivePublicDomain(project,features.publicationDomain)}catch{return derivePublicDomain(project,"fimo.site")}}__name(loadPublicDomain,"loadPublicDomain");function paywallHint(){return"Custom domains require Pay as you go or higher. Add a card at https://fimo.ai/app/billing"}__name(paywallHint,"paywallHint");function isPaywall(err){return err instanceof ApiRequestError&&err.status===403}__name(isPaywall,"isPaywall");function updateErrorToMessage(reason){switch(reason){case"invalid_shape":return"Invalid URL. Use lowercase letters, numbers, and hyphens (max 63 chars).";case"reserved":case"taken_by_project":case"taken_by_legacy_custom_domain":return"This URL is not available.";case"hosting_sync_failed":case"kv_sync_failed":return"Couldn't sync the URL. Try again in a moment.";default:return"Failed to update URL."}}__name(updateErrorToMessage,"updateErrorToMessage");function pad(value,width){return value.length>=width?value:value+" ".repeat(width-value.length)}__name(pad,"pad");function statusLabel2(domain){return domain.status==="active"&&domain.ssl.status==="active"?"verified":domain.ssl.status==="failed"||(domain.ssl.validationErrors?.length??0)>0?"failed":"pending"}__name(statusLabel2,"statusLabel");function renderDnsInstructions(domain){if(domain.dnsAutoConfigured)return"DNS auto-configured by Fimo \u2014 nothing to do.";let rows=[];rows.push({type:"CNAME",name:domain.hostname,value:domain.cnameTarget});for(let record of domain.ownershipVerification??[])rows.push({type:record.type??"TXT",name:record.name,value:record.value});for(let record of domain.ssl.validationRecords??[])record.txtName&&record.txtValue?rows.push({type:"TXT",name:record.txtName,value:record.txtValue}):record.cname&&record.cnameTarget&&rows.push({type:"CNAME",name:record.cname,value:record.cnameTarget});let typeW=Math.max(4,...rows.map(r=>r.type.length)),nameW=Math.max(4,...rows.map(r=>r.name.length)),lines=["","DNS records to add at your registrar:",""];lines.push(` ${pad("TYPE",typeW)} ${pad("NAME",nameW)} VALUE`);for(let r of rows)lines.push(` ${pad(r.type,typeW)} ${pad(r.name,nameW)} ${r.value}`);return lines.join(`
659
+ `)}__name(renderDnsInstructions,"renderDnsInstructions");function parseWait(opts,defaultEnabled){if(opts.noWait)return{enabled:!1,timeoutMs:0};if(opts.wait===void 0||opts.wait===null)return{enabled:defaultEnabled,timeoutMs:300*1e3};if(opts.wait===!0)return{enabled:!0,timeoutMs:300*1e3};let match=String(opts.wait).trim().toLowerCase().match(/^(\d+)(s|m)?$/);if(!match)return{enabled:!0,timeoutMs:300*1e3};let n=parseInt(match[1],10);return{enabled:!0,timeoutMs:(match[2]??"s")==="m"?n*6e4:n*1e3}}__name(parseWait,"parseWait");async function pollUntilVerified(fimo,projectId,initial,timeoutMs){let start=Date.now(),sp=spinner(`Waiting for ${initial.hostname} (SSL: ${initial.ssl.status})`),current=initial;for(;Date.now()-start<timeoutMs;){if(current.status==="active"&&current.ssl.status==="active")return sp.succeed(`Verified \u2014 ${current.hostname} is live with SSL.`),current;if(current.ssl.status==="failed"||(current.ssl.validationErrors?.length??0)>0)return sp.fail(`SSL validation failed for ${current.hostname}.`),current;await new Promise(resolve10=>setTimeout(resolve10,5e3));try{current=await fimo.execute("domains.refresh",{projectId,domainId:initial.id}),sp.update(`Waiting for ${current.hostname} (SSL: ${current.ssl.status})`)}catch(err){return rethrowCliAuthError(err,()=>sp.fail("Authentication required")),isPaywall(err)?(sp.fail(paywallHint()),current):(sp.fail(`Refresh failed: ${err instanceof Error?err.message:String(err)}`),current)}}return sp.fail(`Timed out after ${Math.round(timeoutMs/1e3)}s waiting for ${initial.hostname}.`),current}__name(pollUntilVerified,"pollUntilVerified");async function findDomainByIdOrHostname(fimo,projectId,needle){let domains2=await fimo.execute("domains.list",{projectId}),lower=needle.toLowerCase();return domains2.find(d3=>d3.id===needle||d3.hostname.toLowerCase()===lower)??null}__name(findDomainByIdOrHostname,"findDomainByIdOrHostname");async function domainsListCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId}=resolveProject(options),project=(await fimo.execute("projects.get",{projectId})).data,publicDomain=await loadPublicDomain(fimo,project),domains2=[],domainsBlocked=!1;try{domains2=await fimo.execute("domains.list",{projectId})}catch(err){if(rethrowCliAuthError(err),isPaywall(err))domainsBlocked=!0;else throw err}let subdomain=project.subdomain??project.name,data={defaultUrl:{subdomain,url:`${subdomain}.${publicDomain}`},customDomains:domains2,customDomainsBlocked:domainsBlocked};ui.result({command:"domains list",data,render:__name(()=>{let lines=[];if(lines.push("Default URL"),lines.push(` ${subdomain}.${publicDomain}`),lines.push(""),lines.push("Custom domains"),domainsBlocked)return lines.push(` (${paywallHint()})`),lines.join(`
659
660
  `);if(domains2.length===0)return lines.push(" (none)"),lines.join(`
660
661
  `);let hostW=Math.max(8,...domains2.map(d3=>d3.hostname.length)),statusW=Math.max(8,...domains2.map(d3=>statusLabel2(d3).length));lines.push(` ${pad("HOSTNAME",hostW)} ${pad("STATUS",statusW)} ID`);for(let d3 of domains2)lines.push(` ${pad(d3.hostname,hostW)} ${pad(statusLabel2(d3),statusW)} ${d3.id}`);return lines.join(`
661
662
  `)},"render")})}__name(domainsListCommand,"domainsListCommand");async function domainsRenameDefaultCommand(slug,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId}=resolveProject(options);try{let result=await fimo.execute("domains.renameSubdomain",{projectId,slug}),project=(await fimo.execute("projects.get",{projectId})).data,publicDomain=await loadPublicDomain(fimo,project),url=`${result.subdomain}.${publicDomain}`;ui.ok({command:"domains rename-default",headline:`Default URL is now ${url}`,details:{subdomain:result.subdomain,url}})}catch(err){rethrowCliAuthError(err),ui.error({command:"domains rename-default",code:"SUBDOMAIN_UPDATE_FAILED",message:err instanceof ApiRequestError?updateErrorToMessage(err.detail):"Failed to update URL."})}}__name(domainsRenameDefaultCommand,"domainsRenameDefaultCommand");async function domainsSuggestDefaultCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId}=resolveProject(options),max=options.max?parseInt(options.max,10):5,suggestions=await fimo.execute("domains.suggestSubdomains",{projectId,base:options.base,max:Number.isFinite(max)?Math.min(Math.max(max,1),10):5});if(suggestions.length===0){ui.error({command:"domains suggest-default",code:"NO_SUGGESTIONS_AVAILABLE",message:"No available defaults found.",hint:"Try `fimo domains rename-default <slug>` with your own choice."});return}let project=(await fimo.execute("projects.get",{projectId})).data,publicDomain=await loadPublicDomain(fimo,project);if(options.pick!==void 0){let idx=parseInt(options.pick,10),picked=Number.isFinite(idx)?suggestions[idx]:suggestions.find(s=>s===options.pick);if(!picked){ui.error({command:"domains suggest-default",code:"PICK_NOT_IN_LIST",message:`'${options.pick}' is not in the suggestion list.`});return}await applyClaim(fimo,projectId,picked,publicDomain);return}if(!isInteractive()){ui.result({command:"domains suggest-default",data:{suggestions,publicDomain},render:__name(()=>{let lines=suggestions.map((s,i)=>` ${i}. ${s}.${publicDomain}`);return lines.push("","Pick one in a TTY (omit --json), or pass `--pick <slug>` / `--pick <index>` to claim non-interactively."),lines.join(`
662
- `)},"render")});return}let choice=await _t({message:"Pick a default URL:",options:[...suggestions.map(s=>({value:s,label:`${s}.${publicDomain}`})),{value:"__cancel__",label:"Cancel"}]});if(q(choice)||choice==="__cancel__"){ui.info({command:"domains suggest-default",message:"Cancelled."});return}await applyClaim(fimo,projectId,String(choice),publicDomain)}__name(domainsSuggestDefaultCommand,"domainsSuggestDefaultCommand");async function applyClaim(fimo,projectId,slug,publicDomain){try{let result=await fimo.execute("domains.renameSubdomain",{projectId,slug}),url=`${result.subdomain}.${publicDomain}`;ui.ok({command:"domains suggest-default",headline:`Default URL is now ${url}`,details:{subdomain:result.subdomain,url}})}catch(err){rethrowCliAuthError(err),ui.error({command:"domains suggest-default",code:"SUBDOMAIN_CLAIM_FAILED",message:err instanceof ApiRequestError?updateErrorToMessage(err.detail):"Failed to claim URL."})}}__name(applyClaim,"applyClaim");async function domainsAddCommand(hostname,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId,organizationId}=resolveProject(options),sp=spinner(`Attaching ${hostname}`),domain;try{domain=await fimo.execute("domains.add",{projectId,hostname,redirectToWww:options.redirectWww}),sp.succeed(`Attached ${domain.hostname}`)}catch(err){if(rethrowCliAuthError(err,()=>sp.fail("Authentication required")),sp.stop(),isPaywall(err)){ui.error({command:"domains add",code:"PAYWALL",message:paywallHint(organizationId)});return}if(err instanceof ApiRequestError){if(/fimo_owned_hostname/i.test(err.detail)){ui.error({command:"domains add",code:"FIMO_OWNED_HOSTNAME",message:"That's a Fimo-owned domain.",hint:"Use `fimo domains rename-default` to change your default URL instead."});return}if(/already exists/i.test(err.detail)){ui.error({command:"domains add",code:"DOMAIN_ALREADY_ATTACHED",message:"That domain is already attached.",hint:"Run `fimo domains list` to see current state."});return}}ui.error({command:"domains add",code:"DOMAIN_ADD_FAILED",message:`Failed to add domain: ${err instanceof Error?err.message:String(err)}`});return}let{enabled:waitEnabled,timeoutMs}=parseWait(options,!1);waitEnabled&&!domain.dnsAutoConfigured&&(domain=await pollUntilVerified(fimo,projectId,domain,timeoutMs,organizationId)),ui.result({command:"domains add",data:domain,render:__name(()=>{let lines=[];return lines.push(renderDnsInstructions(domain)),!waitEnabled&&!domain.dnsAutoConfigured&&(lines.push(""),lines.push("Configure these at your registrar, then run:"),lines.push(""),lines.push(` fimo domains refresh ${domain.hostname}`)),lines.push(""),lines.push("Docs: https://fimo.ai/docs/publish/custom-domains"),lines.join(`
663
- `)},"render")})}__name(domainsAddCommand,"domainsAddCommand");async function domainsRemoveCommand(needle,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId,organizationId}=resolveProject(options),domain;try{domain=await findDomainByIdOrHostname(fimo,projectId,needle)}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains remove",code:"PAYWALL",message:paywallHint(organizationId)});return}throw err}if(!domain){ui.error({command:"domains remove",code:"DOMAIN_NOT_FOUND",message:`No custom domain matching '${needle}'.`,hint:"Run `fimo domains list` to see what's attached."});return}if(!options.yes){assertInteractive("Pass --yes to skip confirmation.","domains remove");let confirmed=await ot2({message:`Remove ${domain.hostname}? This detaches it from your project.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"domains remove",message:"Cancelled."});return}}try{await fimo.execute("domains.remove",{projectId,domainId:domain.id}),ui.ok({command:"domains remove",headline:`Removed ${domain.hostname}.`,details:{hostname:domain.hostname,id:domain.id}})}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains remove",code:"PAYWALL",message:paywallHint(organizationId)});return}ui.error({command:"domains remove",code:"DOMAIN_REMOVE_FAILED",message:`Failed to remove domain: ${err instanceof Error?err.message:String(err)}`})}}__name(domainsRemoveCommand,"domainsRemoveCommand");async function domainsRefreshCommand(needle,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId,organizationId}=resolveProject(options),target;try{target=await findDomainByIdOrHostname(fimo,projectId,needle)}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains refresh",code:"PAYWALL",message:paywallHint(organizationId)});return}throw err}if(!target){ui.error({command:"domains refresh",code:"DOMAIN_NOT_FOUND",message:`No custom domain matching '${needle}'.`,hint:"Run `fimo domains list` to see what's attached."});return}let{enabled:waitEnabled,timeoutMs}=parseWait(options,!0),refreshed;try{refreshed=await fimo.execute("domains.refresh",{projectId,domainId:target.id})}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains refresh",code:"PAYWALL",message:paywallHint(organizationId)});return}if(err instanceof ApiRequestError&&err.status===429){ui.error({command:"domains refresh",code:"DOMAIN_REFRESH_RATE_LIMITED",message:"Too many refresh requests. Wait a moment and try again."});return}ui.error({command:"domains refresh",code:"DOMAIN_REFRESH_FAILED",message:`Refresh failed: ${err instanceof Error?err.message:String(err)}`});return}waitEnabled&&(refreshed=await pollUntilVerified(fimo,projectId,refreshed,timeoutMs,organizationId)),ui.result({command:"domains refresh",data:refreshed,render:__name(()=>`${refreshed.hostname}: ${statusLabel2(refreshed)} (SSL: ${refreshed.ssl.status})`,"render")})}__name(domainsRefreshCommand,"domainsRefreshCommand");function resolveOrgId(options){return options.org?options.org:loadProjectSettings(resolveProjectCwd(options.cwd)).organizationId}__name(resolveOrgId,"resolveOrgId");function formatPrice(cents,currency="USD"){return cents==null?"\u2014":new Intl.NumberFormat("en-US",{style:"currency",currency}).format(cents/100)}__name(formatPrice,"formatPrice");function featureDisabledMessage(err){return err instanceof ApiRequestError&&err.status===403&&/disabled/i.test(err.detail)?"Domain purchase is not enabled on this account. Contact support to enable it.":null}__name(featureDisabledMessage,"featureDisabledMessage");async function domainsSearchCommand(keyword,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),tldFilter=options.tld?.split(",").map(s=>s.trim().replace(/^\./,"").toLowerCase()).filter(s=>s.length>0),maxPriceCents=options.maxPrice?Math.round(parseFloat(options.maxPrice)*100):null,limit=options.limit?parseInt(options.limit,10):null,results;try{results=await fimo.execute("registeredDomains.search",{keyword,tldFilter})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains search",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}throw err}let filtered=results.filter(r=>r.available);if(maxPriceCents!==null&&(filtered=filtered.filter(r=>r.price!==null&&r.price<=maxPriceCents)),limit!==null&&Number.isFinite(limit)&&limit>0&&(filtered=filtered.slice(0,limit)),filtered.length===0){ui.info({command:"domains search",message:"No matching available domains."});return}ui.result({command:"domains search",data:{results:filtered},render:__name(()=>{let nameW=Math.max(8,...filtered.map(r=>r.domain.length)),lines=[];lines.push(` ${pad("DOMAIN",nameW)} ${pad("PRICE/yr",10)} RENEWAL/yr`);for(let r of filtered)lines.push(` ${pad(r.domain,nameW)} ${pad(formatPrice(r.price),10)} ${formatPrice(r.renewalPrice)}`);return lines.push(""),lines.push("Buy one with: fimo domains buy <domain>"),lines.join(`
663
+ `)},"render")});return}let choice=await _t({message:"Pick a default URL:",options:[...suggestions.map(s=>({value:s,label:`${s}.${publicDomain}`})),{value:"__cancel__",label:"Cancel"}]});if(q(choice)||choice==="__cancel__"){ui.info({command:"domains suggest-default",message:"Cancelled."});return}await applyClaim(fimo,projectId,String(choice),publicDomain)}__name(domainsSuggestDefaultCommand,"domainsSuggestDefaultCommand");async function applyClaim(fimo,projectId,slug,publicDomain){try{let result=await fimo.execute("domains.renameSubdomain",{projectId,slug}),url=`${result.subdomain}.${publicDomain}`;ui.ok({command:"domains suggest-default",headline:`Default URL is now ${url}`,details:{subdomain:result.subdomain,url}})}catch(err){rethrowCliAuthError(err),ui.error({command:"domains suggest-default",code:"SUBDOMAIN_CLAIM_FAILED",message:err instanceof ApiRequestError?updateErrorToMessage(err.detail):"Failed to claim URL."})}}__name(applyClaim,"applyClaim");async function domainsAddCommand(hostname,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId}=resolveProject(options),sp=spinner(`Attaching ${hostname}`),domain;try{domain=await fimo.execute("domains.add",{projectId,hostname,redirectToWww:options.redirectWww}),sp.succeed(`Attached ${domain.hostname}`)}catch(err){if(rethrowCliAuthError(err,()=>sp.fail("Authentication required")),sp.stop(),isPaywall(err)){ui.error({command:"domains add",code:"PAYWALL",message:paywallHint()});return}if(err instanceof ApiRequestError){if(/fimo_owned_hostname/i.test(err.detail)){ui.error({command:"domains add",code:"FIMO_OWNED_HOSTNAME",message:"That's a Fimo-owned domain.",hint:"Use `fimo domains rename-default` to change your default URL instead."});return}if(/already exists/i.test(err.detail)){ui.error({command:"domains add",code:"DOMAIN_ALREADY_ATTACHED",message:"That domain is already attached.",hint:"Run `fimo domains list` to see current state."});return}}ui.error({command:"domains add",code:"DOMAIN_ADD_FAILED",message:`Failed to add domain: ${err instanceof Error?err.message:String(err)}`});return}let{enabled:waitEnabled,timeoutMs}=parseWait(options,!1);waitEnabled&&!domain.dnsAutoConfigured&&(domain=await pollUntilVerified(fimo,projectId,domain,timeoutMs)),ui.result({command:"domains add",data:domain,render:__name(()=>{let lines=[];return lines.push(renderDnsInstructions(domain)),!waitEnabled&&!domain.dnsAutoConfigured&&(lines.push(""),lines.push("Configure these at your registrar, then run:"),lines.push(""),lines.push(` fimo domains refresh ${domain.hostname}`)),lines.push(""),lines.push("Docs: https://fimo.ai/docs/publish/custom-domains"),lines.join(`
664
+ `)},"render")})}__name(domainsAddCommand,"domainsAddCommand");async function domainsRemoveCommand(needle,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId}=resolveProject(options),domain;try{domain=await findDomainByIdOrHostname(fimo,projectId,needle)}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains remove",code:"PAYWALL",message:paywallHint()});return}throw err}if(!domain){ui.error({command:"domains remove",code:"DOMAIN_NOT_FOUND",message:`No custom domain matching '${needle}'.`,hint:"Run `fimo domains list` to see what's attached."});return}if(!options.yes){assertInteractive("Pass --yes to skip confirmation.","domains remove");let confirmed=await ot2({message:`Remove ${domain.hostname}? This detaches it from your project.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"domains remove",message:"Cancelled."});return}}try{await fimo.execute("domains.remove",{projectId,domainId:domain.id}),ui.ok({command:"domains remove",headline:`Removed ${domain.hostname}.`,details:{hostname:domain.hostname,id:domain.id}})}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains remove",code:"PAYWALL",message:paywallHint()});return}ui.error({command:"domains remove",code:"DOMAIN_REMOVE_FAILED",message:`Failed to remove domain: ${err instanceof Error?err.message:String(err)}`})}}__name(domainsRemoveCommand,"domainsRemoveCommand");async function domainsRefreshCommand(needle,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),{projectId}=resolveProject(options),target;try{target=await findDomainByIdOrHostname(fimo,projectId,needle)}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains refresh",code:"PAYWALL",message:paywallHint()});return}throw err}if(!target){ui.error({command:"domains refresh",code:"DOMAIN_NOT_FOUND",message:`No custom domain matching '${needle}'.`,hint:"Run `fimo domains list` to see what's attached."});return}let{enabled:waitEnabled,timeoutMs}=parseWait(options,!0),refreshed;try{refreshed=await fimo.execute("domains.refresh",{projectId,domainId:target.id})}catch(err){if(rethrowCliAuthError(err),isPaywall(err)){ui.error({command:"domains refresh",code:"PAYWALL",message:paywallHint()});return}if(err instanceof ApiRequestError&&err.status===429){ui.error({command:"domains refresh",code:"DOMAIN_REFRESH_RATE_LIMITED",message:"Too many refresh requests. Wait a moment and try again."});return}ui.error({command:"domains refresh",code:"DOMAIN_REFRESH_FAILED",message:`Refresh failed: ${err instanceof Error?err.message:String(err)}`});return}waitEnabled&&(refreshed=await pollUntilVerified(fimo,projectId,refreshed,timeoutMs)),ui.result({command:"domains refresh",data:refreshed,render:__name(()=>`${refreshed.hostname}: ${statusLabel2(refreshed)} (SSL: ${refreshed.ssl.status})`,"render")})}__name(domainsRefreshCommand,"domainsRefreshCommand");function resolveOrgId(options){return options.org?options.org:loadProjectSettings(resolveProjectCwd(options.cwd)).organizationId}__name(resolveOrgId,"resolveOrgId");function formatPrice(cents,currency="USD"){return cents==null?"\u2014":new Intl.NumberFormat("en-US",{style:"currency",currency}).format(cents/100)}__name(formatPrice,"formatPrice");function featureDisabledMessage(err){return err instanceof ApiRequestError&&err.status===403&&/disabled/i.test(err.detail)?"Domain purchase is not enabled on this account. Contact support to enable it.":null}__name(featureDisabledMessage,"featureDisabledMessage");async function domainsSearchCommand(keyword,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),tldFilter=options.tld?.split(",").map(s=>s.trim().replace(/^\./,"").toLowerCase()).filter(s=>s.length>0),maxPriceCents=options.maxPrice?Math.round(parseFloat(options.maxPrice)*100):null,limit=options.limit?parseInt(options.limit,10):null,results;try{results=await fimo.execute("registeredDomains.search",{keyword,tldFilter})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains search",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}throw err}let filtered=results.filter(r=>r.available);if(maxPriceCents!==null&&(filtered=filtered.filter(r=>r.price!==null&&r.price<=maxPriceCents)),limit!==null&&Number.isFinite(limit)&&limit>0&&(filtered=filtered.slice(0,limit)),filtered.length===0){ui.info({command:"domains search",message:"No matching available domains."});return}ui.result({command:"domains search",data:{results:filtered},render:__name(()=>{let nameW=Math.max(8,...filtered.map(r=>r.domain.length)),lines=[];lines.push(` ${pad("DOMAIN",nameW)} ${pad("PRICE/yr",10)} RENEWAL/yr`);for(let r of filtered)lines.push(` ${pad(r.domain,nameW)} ${pad(formatPrice(r.price),10)} ${formatPrice(r.renewalPrice)}`);return lines.push(""),lines.push("Buy one with: fimo domains buy <domain>"),lines.join(`
664
665
  `)},"render")})}__name(domainsSearchCommand,"domainsSearchCommand");async function domainsPricingCommand(domain,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),pricing;try{pricing=await fimo.execute("registeredDomains.pricing",{domain})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains pricing",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}throw err}let years=options.years?parseInt(options.years,10):1,total=pricing.price!==null?pricing.price*years:null;ui.result({command:"domains pricing",data:{...pricing,years,totalCents:total,totalFormatted:formatPrice(total)},render:__name(()=>{let lines=[];return lines.push(`${pricing.domain}${pricing.premium?" (PREMIUM)":""}`),lines.push(` Purchase: ${formatPrice(pricing.price)} \xD7 ${years} year${years===1?"":"s"} = ${formatPrice(total)}`),lines.push(` Renewal: ${formatPrice(pricing.renewalPrice)}/year`),pricing.allowedYears.length>0&&lines.push(` Allowed years: ${pricing.allowedYears.join(", ")}`),lines.join(`
665
666
  `)},"render")})}__name(domainsPricingCommand,"domainsPricingCommand");async function domainsBuyCommand(domain,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),organizationId=resolveOrgId(options),years=options.years?parseInt(options.years,10):void 0,autoRenew=options.autoRenew,pricing;try{pricing=await fimo.execute("registeredDomains.pricing",{domain})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains buy",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError){ui.error({command:"domains buy",code:"PRICING_FETCH_FAILED",message:`Couldn't fetch pricing for ${domain}: ${err.detail}`});return}throw err}if(pricing.price===null){ui.error({command:"domains buy",code:"DOMAIN_UNAVAILABLE",message:`${domain} is not available for registration.`});return}if(pricing.premium){ui.error({command:"domains buy",code:"PREMIUM_DOMAIN_UNSUPPORTED",message:`${domain} is a premium domain and isn't supported through the CLI.`});return}let effectiveYears=years??Math.min(pricing.allowedYears[0]??1,1),totalCents=pricing.price*effectiveYears;if(!options.yes){assertInteractive("Pass --yes to skip the confirmation prompt.","domains buy"),O2.message(`${domain}
666
667
  Purchase: ${formatPrice(pricing.price)} \xD7 ${effectiveYears} year${effectiveYears===1?"":"s"} = ${formatPrice(totalCents)}
@@ -929,7 +930,7 @@ Run \`fimo mcp <command> --help\` for command-specific help.
929
930
  `),ui.ok({command:"projects rename",headline:`Renamed to "${name}".`,details:{project_id:local.projectId,display_name:name},warnings:["Local config changed. Later remote config commands may require reconciliation. Finish your local edits, then run `fimo deploy --no-wait` when ready for a quick sync."]})}__name(projectsRenameCommand,"projectsRenameCommand");async function projectsPublishCommand(projectIdArg,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),publication=createPublicationControlService(cfg),projectId=resolveProjectId8(projectIdArg,options,"projects publish");if(!projectId)return;let sp=spinner(`Publishing ${projectId}`),publicationId;try{publicationId=await publication.publish(projectId),sp.succeed("Published")}catch(error){rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail();let failedPublicationId=publicationIdFromError(error);ui.error({command:"projects publish",code:"PROJECT_PUBLISH_FAILED",message:`Publish failed: ${error instanceof Error?error.message:String(error)}`,...failedPublicationId?{details:{publication_id:failedPublicationId},hint:`Run \`fimo publish inspect ${failedPublicationId}\` for the recorded attempt.`}:{}});return}let appUrl=null;try{let{data:fresh}=await fimo.execute("projects.get",{projectId});appUrl=fresh.appUrl??null}catch{}ui.ok({command:"projects publish",headline:appUrl?`Live at ${appUrl}`:`Published ${projectId}.`,details:{project_id:projectId,app_url:appUrl,publication_id:publicationId}})}__name(projectsPublishCommand,"projectsPublishCommand");async function projectsUnpublishCommand(projectIdArg,options){let cfg=loadConfig(),publication=createPublicationControlService(cfg),projectId=resolveProjectId8(projectIdArg,options,"projects unpublish");if(!projectId)return;let sp=spinner(`Unpublishing ${projectId}`);try{await publication.unpublish(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");async function projectsTransferCommand(projectIdArg,options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),projectId=resolveProjectId8(projectIdArg,options,"projects transfer");if(!projectId)return;if(!options.to){ui.error({command:"projects transfer",code:"NO_TARGET_ORGANIZATION",message:"No destination organization given.",hint:"Pass --to <organization id or slug>. Run `fimo orgs list` to see yours."});return}let orgs2;try{({data:orgs2}=await fimo.execute("organizations.list",{}))}catch(error){rethrowCliAuthError(error),ui.error({command:"projects transfer",code:"ORGANIZATION_LOOKUP_FAILED",message:`Could not list your organizations (${describeRequestFailure(error)}).`,hint:"Retry, then run `fimo orgs list` to confirm the destination exists.",...error instanceof ApiRequestError?{details:{status:error.status}}:{}});return}let target=orgs2.find(org=>org.id===options.to)??orgs2.find(org=>org.slug===options.to);if(!target){ui.error({command:"projects transfer",code:"ORGANIZATION_NOT_FOUND",message:`No organization matched "${options.to}".`,hint:"Run `fimo orgs list` to see the organizations you belong to."});return}if(!options.yes){assertInteractive("Pass --yes to skip confirmation.","projects transfer");let confirmed=await ot2({message:`Transfer project ${projectId} to ${target.name}? The current organization loses access.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"projects transfer",message:"Cancelled."});return}}let sp=spinner(`Transferring ${projectId} to ${target.name}`),result;try{result=await fimo.execute("projects.transfer",{projectId,targetOrganizationId:target.id}),sp.succeed("Transferred")}catch(error){if(error instanceof ApiRequestError&&error.status===403&&error.code!=="target_organization_forbidden")throw new PermissionDeniedError(cfg.apiUrl,requiredPermissions(error.body));rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail(),ui.error({command:"projects transfer",...transferError(error,target.name)});return}let markerUpdated=readLocalConfig(options)?.projectId===projectId;markerUpdated&&updateLocalProjectOrganization(resolveCwd2(options),target.id),ui.ok({command:"projects transfer",headline:`Transferred ${projectId} to ${target.name}.`,details:{project_id:projectId,organization_id:target.id,organization_name:target.name,moved_threads:result.movedThreads,revoked_invites:result.revokedInvites,revoked_grants:result.revokedGrants,marker_updated:markerUpdated},...result.warnings.length>0?{warnings:result.warnings}:{}})}__name(projectsTransferCommand,"projectsTransferCommand");function transferError(error,targetName){let blockers=transferBlockersFromError(error);if(blockers.length>0)return{code:"PROJECT_TRANSFER_BLOCKED",message:blockers.map(blocker=>blocker.message).join(" "),details:{reason:"project_transfer_blocked",blockers:blockers.map(blocker=>blocker.code)}};let reason=error instanceof ApiRequestError?error.code:void 0,details=reason?{reason}:void 0;switch(reason){case"project_transfer_in_progress":return{code:"PROJECT_TRANSFER_IN_PROGRESS",message:"Another transfer is already running for this project.",hint:"Retry shortly. If this persists, ask support to inspect the project transfer lease.",details};case"target_organization_forbidden":return{code:"ORGANIZATION_FORBIDDEN",message:`You are not an admin or owner of ${targetName}.`,hint:"Ask an owner of the destination organization to run the transfer, or to make you an admin.",details};case"target_organization_not_found":return{code:"ORGANIZATION_NOT_FOUND",message:`${targetName} is no longer available as a destination.`,hint:"Run `fimo orgs list` to see the organizations you belong to.",details};case"target_subscription_inactive":return{code:"SUBSCRIPTION_REQUIRED",message:`${targetName} needs an active paid plan before it can receive a project.`,hint:"Start a plan for the destination organization, then retry.",details};case"project_not_found":return{code:"PROJECT_NOT_FOUND",message:"Project not found.",details};default:return{code:"PROJECT_TRANSFER_FAILED",message:`Transfer failed: ${describeRequestFailure(error)}.`,details}}}__name(transferError,"transferError");function describeRequestFailure(error){return error instanceof ApiRequestError?`HTTP ${error.status}`:error instanceof Error?error.message:String(error)}__name(describeRequestFailure,"describeRequestFailure");init_dist();init_config();init_sdk_transport();init_project();var MAX_LIMIT2=100,MAX_LOG_LIMIT=1e3;async function publishListCommand(options){let projectId=resolveProjectId9(options,"publish list");if(!projectId)return;let pagination;try{pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:MAX_LIMIT2,legacyCursor:"before"})}catch(error){ui.error({command:"publish list",code:error instanceof PaginationValidationError&&error.kind!=="invalid_limit"?"PUBLICATION_INVALID_CURSOR":"PUBLICATION_INVALID_LIMIT",message:errorMessage4(error)});return}let fimo=createCliFimoClient(loadConfig()),page;try{page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>projectPublicationsPage2(await fimo.execute("publications.list",{projectId,limit:pagination.limit,cursor})),"fetchPage")})}catch(error){rethrowCliAuthError(error),ui.error({command:"publish list",code:"PUBLICATION_REQUEST_FAILED",message:`Could not read publication history: ${errorMessage4(error)}`});return}let hint=page.nextCursor?buildOlderHint2(page.nextCursor,pagination.limit,options):void 0;ui.result({command:"publish list",data:{project_id:projectId,...page},render:__name(()=>renderPublicationList(page),"render"),...hint?{hint}:{}})}__name(publishListCommand,"publishListCommand");async function publishInspectCommand(publicationId,options){let projectId=resolveProjectId9(options,"publish inspect");if(!projectId)return;let fimo=createCliFimoClient(loadConfig()),publication;try{publication=projectPublication2(await fimo.execute("publications.get",{projectId,publicationId}))}catch(error){rethrowCliAuthError(error),ui.error({command:"publish inspect",code:"PUBLICATION_NOT_FOUND",message:`Could not read publication ${publicationId}: ${errorMessage4(error)}`,hint:"Run `fimo publish list` to see this project's publications."});return}ui.result({command:"publish inspect",data:{project_id:projectId,...publication},render:__name(()=>renderPublication(publication),"render")})}__name(publishInspectCommand,"publishInspectCommand");async function publishLogsCommand(publicationId,options){let projectId=resolveProjectId9(options,"publish logs");if(!projectId)return;await requireOperation("fimo.logs.read",{projectId});let limit;try{limit=parseLimit(options.limit,MAX_LOG_LIMIT)}catch(error){ui.error({command:"publish logs",code:"PUBLICATION_INVALID_LIMIT",message:errorMessage4(error)});return}let fimo=createCliFimoClient(loadConfig()),result;try{result=projectPublicationLogs2(await fimo.execute("publications.logs",{projectId,publicationId,limit}))}catch(error){if(rethrowCliAuthError(error),error instanceof ApiRequestError&&error.status===404){ui.error({command:"publish logs",code:"PUBLICATION_NOT_FOUND",message:`Publication ${publicationId} does not exist in this project.`,hint:"Run `fimo publish list` to see this project's publications."});return}ui.error({command:"publish logs",code:"PUBLICATION_REQUEST_FAILED",message:`Could not read publication logs: ${errorMessage4(error)}`});return}let data={project_id:projectId,...result};if(result.status==="unavailable"){let{message}=result;ui.result({command:"publish logs",data,render:__name(()=>message,"render")});return}ui.result({command:"publish logs",data,render:__name(()=>renderPublicationLogs(result),"render")})}__name(publishLogsCommand,"publishLogsCommand");function projectPublication2(publication){let{targetBranch,...source}=publication.source;return{...publication,source:{...source,targetEnv:targetBranch}}}__name(projectPublication2,"projectPublication");function projectPublicationsPage2(page){return{...page,items:page.items.map(projectPublication2)}}__name(projectPublicationsPage2,"projectPublicationsPage");function projectPublicationLogs2(result){return result.status==="unavailable"?{status:result.status,publicationId:result.publicationId,reason:result.reason,message:result.message}:{status:result.status,publicationId:result.publicationId,events:result.items}}__name(projectPublicationLogs2,"projectPublicationLogs");function resolveProjectId9(options,command){try{return loadProjectSettings(resolveProjectCwd(options.cwd)).projectId}catch{return ui.error({command,code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"cd into a linked project first."}),null}}__name(resolveProjectId9,"resolveProjectId");function parseLimit(value,max=MAX_LIMIT2){if(value===void 0)return;let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>max)throw new Error(`--limit must be an integer between 1 and ${max}.`);return limit}__name(parseLimit,"parseLimit");function renderPublicationList(page){if(page.items.length===0)return"No publications yet. Run `fimo deploy --publish` to publish this project.";let lines=page.items.map(item=>{let parts=[item.createdAt,item.status.padEnd(9),item.id];return item.label&&parts.push(item.label),item.failureCode?parts.push(item.failureCode):item.url&&parts.push(item.url),parts.join(" ")});return lines.push(""),lines.push("Publications are kept for the life of the project."),lines.join(`
930
931
  `)}__name(renderPublicationList,"renderPublicationList");function renderPublication(publication){let lines=[`Publication: ${publication.id}`,`Status: ${publication.status}`,`Source: ${publication.source.branch} -> ${publication.source.targetEnv}`,`Started: ${publication.createdAt}`,`Finished: ${publication.finishedAt??"still running"}`];return publication.label&&lines.push(`Label: ${publication.label}`),publication.source.commit&&lines.push(`Commit: ${publication.source.commit}`),(publication.source.framework||publication.source.configVersion)&&lines.push(`Project: ${publication.source.framework??"unknown framework"}, config v${publication.source.configVersion??"?"}`),publication.url&&lines.push(`URL: ${publication.url}`),publication.failureCode&&lines.push(`Failure: ${publication.failureCode}`),publication.notes&&lines.push(`Notes: ${publication.notes}`),lines.join(`
931
932
  `)}__name(renderPublication,"renderPublication");function renderPublicationLogs(page){let count=page.events.length,lines=[`Publication ${page.publicationId}: ${count} ${count===1?"event":"events"}`];lines.push("");for(let event of page.events)lines.push(`${logMarker(event)}${event.message}`);return lines.join(`
932
- `)}__name(renderPublicationLogs,"renderPublicationLogs");function logMarker(event){switch(event.stream){case"command":return"$ ";case"stderr":case"error":return"! ";case"status":return"# ";default:return" "}}__name(logMarker,"logMarker");function buildOlderHint2(cursor,limit,options){let trailingArgs=[];return options.cwd&&trailingArgs.push("--cwd",options.cwd),buildPaginationHint(["fimo","publish","list"],{cursor,limit,trailingArgs},"Older")}__name(buildOlderHint2,"buildOlderHint");function errorMessage4(error){return error instanceof Error?error.message:String(error)}__name(errorMessage4,"errorMessage");init_esm();init_dist();init_config();init_sdk_transport();init_project_services();init_project_context();init_project();var PUBLISH_SUBCOMMANDS=new Set(["list","inspect","logs"]),GLOBAL_VALUE_OPTIONS=new Set(["--branch"]),PUBLISH_VALUE_OPTIONS=new Set(["-C","--cwd","--label","--notes"]);function hasRemovedPublishVersion(argv){let commandIndex=-1;for(let index=2;index<argv.length;index+=1){let arg=argv[index];if(GLOBAL_VALUE_OPTIONS.has(arg))index+=1;else if(!arg.startsWith("-")){commandIndex=index;break}}if(commandIndex===-1||argv[commandIndex]!=="publish")return!1;for(let index=commandIndex+1;index<argv.length;index+=1){let arg=argv[index];if(PUBLISH_VALUE_OPTIONS.has(arg)){index+=1;continue}if(arg==="--version"||arg.startsWith("--version="))return!0;if(PUBLISH_SUBCOMMANDS.has(arg))return!1}return!1}__name(hasRemovedPublishVersion,"hasRemovedPublishVersion");function rejectRemovedPublishVersion(){ui.error({command:"publish",code:"PUBLISH_VERSION_REMOVED",message:"--version is no longer supported. Fimo assigns every publication a stable ID.",hint:"Use `--label <text>` if you want a human-readable publication annotation."})}__name(rejectRemovedPublishVersion,"rejectRemovedPublishVersion");async function publishCommand(options,cmd){if(options.version!==void 0){rejectRemovedPublishVersion();return}if(process.env.FIMO_MIGRATION_NO_DEPLOY==="1"){ui.error({command:"publish",code:"MIGRATION_DEPLOY_BLOCKED",message:"Publishing is disabled while a migration is running.",hint:"Finish local migration and QA first, then request deployment separately."});return}let program2=cmd?.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),cwd=resolveProjectCwd(options.cwd),fimo=createCliFimoClient(loadConfig(),ctx.branch),publication=createPublicationControlService(loadConfig(),ctx.branch),{data:project}=await fimo.execute("projects.get",{projectId:ctx.projectId}),productionSourceBranch=project.productionSourceBranch??DEFAULT_BRANCH;if(ctx.branch!==productionSourceBranch){ui.error({command:"publish",code:"PUBLISH_REQUIRES_SOURCE_BRANCH",message:`Refusing to publish from Branch '${ctx.branch}'. Production publishes from '${productionSourceBranch}'.`,hint:`Switch Branches first: \`fimo checkout ${productionSourceBranch}\`.`});return}if(!options.skipValidate){let sp=spinner("Running lint + codegen + smoke checks"),report=await runValidate({cwd,branchOverride:branchOverride2});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")}let request={...options.label===void 0?{}:{label:options.label},...options.notes===void 0?{}:{notes:options.notes}},publishSp=spinner("Publishing (this can take a few minutes)"),publicationId;try{publicationId=await publication.publish(ctx.projectId,request)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail();let failedPublicationId=publicationIdFromError(error);ui.error({command:"publish",code:"PUBLISH_FAILED",message:`Publish failed: ${errorMessage5(error)}`,...failedPublicationId?{details:{publication_id:failedPublicationId},hint:`Run \`fimo publish inspect ${failedPublicationId}\` for the recorded attempt.`}:{}});return}publishSp.succeed("Published");let appUrl=null;try{appUrl=(await fimo.execute("projects.get",{projectId:ctx.projectId})).data.appUrl??null}catch{}ui.ok({command:"publish",headline:appUrl?`Live at ${appUrl}`:"Published.",details:{publication_id:publicationId,app_url:appUrl,...options.label===void 0?{}:{label:options.label}},...publicationId?{hint:`Inspect it with \`fimo publish inspect ${publicationId}\`.`}:{}})}__name(publishCommand,"publishCommand");function errorMessage5(error){return error instanceof Error?error.message:String(error)}__name(errorMessage5,"errorMessage");init_dist();init_auth();init_config();init_sdk_transport();init_project_services();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 createCliFimoClient(cfg).execute("referrals.summary",{userId: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 createIdentityService(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();import fs44 from"node:fs";import path45 from"node:path";async function rulesSyncCommand(options={}){let cwd=path45.resolve(options.cwd??process.cwd()),agentsMdPath=path45.join(cwd,"AGENTS.md");if(!fs44.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)),data={synced:result.perAgentVariants,skipped:result.perAgentVariantsSkipped,nativeAgentsMd:noVariantAgents};ui.result({command:"rules sync",data,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(`
933
+ `)}__name(renderPublicationLogs,"renderPublicationLogs");function logMarker(event){switch(event.stream){case"command":return"$ ";case"stderr":case"error":return"! ";case"status":return"# ";default:return" "}}__name(logMarker,"logMarker");function buildOlderHint2(cursor,limit,options){let trailingArgs=[];return options.cwd&&trailingArgs.push("--cwd",options.cwd),buildPaginationHint(["fimo","publish","list"],{cursor,limit,trailingArgs},"Older")}__name(buildOlderHint2,"buildOlderHint");function errorMessage4(error){return error instanceof Error?error.message:String(error)}__name(errorMessage4,"errorMessage");init_esm();init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_git();init_project_context();init_project();var PUBLISH_SUBCOMMANDS=new Set(["list","inspect","logs"]),GLOBAL_VALUE_OPTIONS=new Set(["--branch"]),PUBLISH_VALUE_OPTIONS=new Set(["-C","--cwd","--label","--notes"]);function hasRemovedPublishVersion(argv){let commandIndex=-1;for(let index=2;index<argv.length;index+=1){let arg=argv[index];if(GLOBAL_VALUE_OPTIONS.has(arg))index+=1;else if(!arg.startsWith("-")){commandIndex=index;break}}if(commandIndex===-1||argv[commandIndex]!=="publish")return!1;for(let index=commandIndex+1;index<argv.length;index+=1){let arg=argv[index];if(PUBLISH_VALUE_OPTIONS.has(arg)){index+=1;continue}if(arg==="--version"||arg.startsWith("--version="))return!0;if(PUBLISH_SUBCOMMANDS.has(arg))return!1}return!1}__name(hasRemovedPublishVersion,"hasRemovedPublishVersion");function rejectRemovedPublishVersion(){ui.error({command:"publish",code:"PUBLISH_VERSION_REMOVED",message:"--version is no longer supported. Fimo assigns every publication a stable ID.",hint:"Use `--label <text>` if you want a human-readable publication annotation."})}__name(rejectRemovedPublishVersion,"rejectRemovedPublishVersion");async function publishCommand(options,cmd){if(options.version!==void 0){rejectRemovedPublishVersion();return}if(process.env.FIMO_MIGRATION_NO_DEPLOY==="1"){ui.error({command:"publish",code:"MIGRATION_DEPLOY_BLOCKED",message:"Publishing is disabled while a migration is running.",hint:"Finish local migration and QA first, then request deployment separately."});return}let program2=cmd?.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),cwd=resolveProjectCwd(options.cwd),fimo=createCliFimoClient(loadConfig(),ctx.branch),publication=createPublicationControlService(loadConfig(),ctx.branch),{data:project}=await fimo.execute("projects.get",{projectId:ctx.projectId}),productionSourceBranch=project.productionSourceBranch??DEFAULT_BRANCH;if(ctx.branch!==productionSourceBranch){ui.error({command:"publish",code:"PUBLISH_REQUIRES_SOURCE_BRANCH",message:`Refusing to publish from Branch '${ctx.branch}'. Production publishes from '${productionSourceBranch}'.`,hint:`Switch Branches first: \`fimo checkout ${productionSourceBranch}\`.`});return}let source=await inspectSource(cwd,ctx),warnings=publishSourceWarnings(source,ctx.branch);for(let warning of warnings)ui.warn({command:"publish",message:warning});if(!options.skipValidate){let sp=spinner("Running lint + codegen + smoke checks"),report=await runValidate({cwd,branchOverride:branchOverride2});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")}let request={...options.label===void 0?{}:{label:options.label},...options.notes===void 0?{}:{notes:options.notes}},publishSp=spinner("Publishing (this can take a few minutes)"),publicationId;try{publicationId=await publication.publish(ctx.projectId,request)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail();let failedPublicationId=publicationIdFromError(error);ui.error({command:"publish",code:"PUBLISH_FAILED",message:`Publish failed: ${errorMessage5(error)}`,...failedPublicationId?{details:{publication_id:failedPublicationId},hint:`Run \`fimo publish inspect ${failedPublicationId}\` for the recorded attempt.`}:{}});return}publishSp.succeed("Published");let[appUrl,built]=await Promise.all([fimo.execute("projects.get",{projectId:ctx.projectId}).then(({data})=>data.appUrl??null).catch(()=>null),builtCommit(fimo,ctx.projectId,publicationId,cwd)]),resultWarnings=[...warnings,...builtCommitWarnings(source,built,publicationId,ctx.branch)];ui.ok({command:"publish",headline:appUrl?`Live at ${appUrl}`:"Published.",details:{publication_id:publicationId,app_url:appUrl,...built===null?{}:{source_commit:built.commit},...built?.subject==null?{}:{source_commit_subject:built.subject},...options.label===void 0?{}:{label:options.label}},...resultWarnings.length>0?{warnings:resultWarnings}:{},...publicationId?{hint:`Inspect it with \`fimo publish inspect ${publicationId}\`.`}:{}})}__name(publishCommand,"publishCommand");async function inspectSource(cwd,ctx){try{let remote=await createGitService(loadConfig(),ctx.branch).getRemote(ctx.projectId,ctx.branch);return await inspectPublishSource({cwd,remoteBranch:remote.branch,remoteUrl:remote.url})}catch(error){return rethrowCliAuthError(error),{status:"unavailable",reason:`the Fimo remote could not be resolved (${errorMessage5(error)})`}}}__name(inspectSource,"inspectSource");function publishSourceWarnings(source,branch){if(source.status==="unavailable")return[`Could not compare this checkout with fimo/${branch}: ${source.reason}. Publishing whatever the Fimo remote holds; local commits that were never deployed are not included.`];let warnings=[];if(source.unpushed>0){let plural=source.unpushed===1?"commit is":"commits are";warnings.push(`${source.unpushed} local ${plural} not on fimo/${branch} and will not be published. \`fimo publish\` never pushes; run \`fimo deploy --publish\` to push and publish your local commits.`)}return source.dirty&&warnings.push("Uncommitted changes in the working tree are not published. Commit them and deploy first."),warnings}__name(publishSourceWarnings,"publishSourceWarnings");async function builtCommit(fimo,projectId,publicationId,cwd){if(!publicationId)return null;try{let{source}=await fimo.execute("publications.get",{projectId,publicationId});return source.commit?{commit:source.commit,subject:await commitSubjectOrNull(cwd,source.commit)}:null}catch{return null}}__name(builtCommit,"builtCommit");function builtCommitWarnings(source,built,publicationId,branch){return built===null?["Could not confirm which commit this publication built."+(publicationId?` Run \`fimo publish inspect ${publicationId}\` to read it from the record.`:"")]:source.status==="known"&&source.remoteHead!==built.commit?[`fimo/${branch} moved while this command ran: the local comparison used ${source.remoteHead.slice(0,7)}, but the publish built ${built.commit.slice(0,7)}.`]:[]}__name(builtCommitWarnings,"builtCommitWarnings");function errorMessage5(error){return error instanceof Error?error.message:String(error)}__name(errorMessage5,"errorMessage");init_dist();init_auth();init_config();init_sdk_transport();init_project_services();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 createCliFimoClient(cfg).execute("referrals.summary",{userId: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 createIdentityService(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();import fs44 from"node:fs";import path45 from"node:path";async function rulesSyncCommand(options={}){let cwd=path45.resolve(options.cwd??process.cwd()),agentsMdPath=path45.join(cwd,"AGENTS.md");if(!fs44.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)),data={synced:result.perAgentVariants,skipped:result.perAgentVariantsSkipped,nativeAgentsMd:noVariantAgents};ui.result({command:"rules sync",data,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(`
933
934
  `))},"render")})}__name(rulesSyncCommand,"rulesSyncCommand");init_esm();init_dist();init_config();init_sdk_transport();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"];function withLegacyEnvironment(value){let{branch,...record}=value;return{...record,env:branch}}__name(withLegacyEnvironment,"withLegacyEnvironment");var ScheduleCommandError=class extends Error{static{__name(this,"ScheduleCommandError")}code;constructor(code2,message){super(message),this.name="ScheduleCommandError",this.code=code2}};function collect3(value,previous){return[...previous??[],value]}__name(collect3,"collect");function addScopeOptions4(command){return command.option("--branch <branch>","Target a specific Fimo Branch (defaults to the current git branch)").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions4,"addScopeOptions");function registerSchedulesCommands(program2){let schedules=program2.command("schedules").description("Manage recurring project commands").addHelpText("after",`
934
935
  Examples:
935
936
  fimo schedules create nightly --cron "0 2 * * *" --do "fimo validate" --secret CMS_TOKEN