fimo 2.8.0-staging.8 → 2.8.0-staging.9

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 (54) hide show
  1. package/assets/skills/fimo-studio/SKILL.md +9 -0
  2. package/assets/skills/fimo-studio/references/ai-chat.md +9 -1
  3. package/assets/skills/fimo-studio/references/billing-and-credits.md +2 -2
  4. package/assets/skills/fimo-studio/references/cms.md +1 -1
  5. package/assets/skills/fimo-studio/references/command-palette.md +1 -0
  6. package/assets/skills/fimo-studio/references/connections.md +1 -2
  7. package/assets/skills/fimo-studio/references/custom-domains.md +2 -2
  8. package/assets/skills/fimo-studio/references/media-library.md +1 -2
  9. package/assets/skills/fimo-studio/references/preview-and-responsive.md +4 -9
  10. package/assets/skills/fimo-studio/references/project-creation.md +22 -6
  11. package/assets/skills/fimo-studio/references/publish-and-deploy.md +2 -2
  12. package/assets/skills/fimo-studio/references/schedules.md +2 -3
  13. package/assets/skills/fimo-studio/references/seo-settings.md +2 -2
  14. package/assets/skills/fimo-studio/references/sharing-and-collaboration.md +2 -3
  15. package/assets/skills/fimo-studio/references/visual-editing.md +1 -1
  16. package/assets/skills/fimo-studio/references/webhooks.md +5 -6
  17. package/dist/cli/bundle.json +1 -1
  18. package/dist/cli/index.js +9 -9
  19. package/dist/runtime/templates.d.ts +0 -1
  20. package/dist/runtime/templates.js +0 -3
  21. package/package.json +8 -8
  22. package/templates/astro/package.json +3 -3
  23. package/templates/nextjs/package.json +4 -4
  24. package/templates/react-router/package.json +5 -5
  25. package/templates/sveltekit/package.json +3 -3
  26. package/templates/vite/package.json +5 -5
  27. package/templates/welcome/manifest.json +0 -655
  28. package/templates/welcome/media/analytics-overview.avif +0 -0
  29. package/templates/welcome/media/autonomous-loop.avif +0 -0
  30. package/templates/welcome/media/editable-preview.avif +0 -0
  31. package/templates/welcome/media/media-library.avif +0 -0
  32. package/templates/welcome/media/slack-teams.avif +0 -0
  33. package/templates/welcome/template/.fimo/agents/welcome-guide/GOAL.md +0 -12
  34. package/templates/welcome/template/.fimo/agents/welcome-guide/capabilities.yaml +0 -3
  35. package/templates/welcome/template/.fimo/agents/welcome-guide/config.yaml +0 -8
  36. package/templates/welcome/template/.fimo/config.json +0 -52
  37. package/templates/welcome/template/src/font.css +0 -60
  38. package/templates/welcome/template/src/pages/ArticleDetail.tsx +0 -104
  39. package/templates/welcome/template/src/pages/Index.tsx +0 -36
  40. package/templates/welcome/template/src/pages/SiteContent.tsx +0 -674
  41. package/templates/welcome/template/src/pages/fallback-content.ts +0 -152
  42. package/templates/welcome/template/src/routes.ts +0 -9
  43. package/templates/welcome/template/src/schemas/Article.json +0 -34
  44. package/templates/welcome/template/src/schemas/Article.ts +0 -54
  45. package/templates/welcome/template/src/schemas/Article.types.ts +0 -93
  46. package/templates/welcome/template/src/schemas/Author.json +0 -17
  47. package/templates/welcome/template/src/schemas/Author.ts +0 -51
  48. package/templates/welcome/template/src/schemas/Author.types.ts +0 -54
  49. package/templates/welcome/template/src/schemas/Category.json +0 -17
  50. package/templates/welcome/template/src/schemas/Category.ts +0 -51
  51. package/templates/welcome/template/src/schemas/Category.types.ts +0 -54
  52. package/templates/welcome/template/src/schemas/HomePage.json +0 -110
  53. package/templates/welcome/template/src/schemas/HomePage.ts +0 -22
  54. package/templates/welcome/template/src/schemas/HomePage.types.ts +0 -116
package/dist/cli/index.js CHANGED
@@ -177,7 +177,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
177
177
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
178
178
  `,nl)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(map){let it2=map.items[map.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,it2.value){let end="end"in it2.value?it2.value.end:void 0;(Array.isArray(end)?end[end.length-1]:void 0)?.type==="comment"?end?.push(this.sourceToken):map.items.push({start:[this.sourceToken]})}else it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)map.items.push({start:[this.sourceToken]});else if(it2.sep)it2.sep.push(this.sourceToken);else{if(this.atIndentedComment(it2.start,map.indent)){let end=map.items[map.items.length-2]?.value?.end;if(Array.isArray(end)){Array.prototype.push.apply(end,it2.start),end.push(this.sourceToken),map.items.pop();return}}it2.start.push(this.sourceToken)}return}if(this.indent>=map.indent){let atMapIndent=!this.onKeyLine&&this.indent===map.indent,atNextItem=atMapIndent&&(it2.sep||it2.explicitKey)&&this.type!=="seq-item-ind",start=[];if(atNextItem&&it2.sep&&!it2.value){let nl=[];for(let i=0;i<it2.sep.length;++i){let st2=it2.sep[i];switch(st2.type){case"newline":nl.push(i);break;case"space":break;case"comment":st2.indent>map.indent&&(nl.length=0);break;default:nl.length=0}}nl.length>=2&&(start=it2.sep.splice(nl[1]))}switch(this.type){case"anchor":case"tag":atNextItem||it2.value?(start.push(this.sourceToken),map.items.push({start}),this.onKeyLine=!0):it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"explicit-key-ind":!it2.sep&&!it2.explicitKey?(it2.start.push(this.sourceToken),it2.explicitKey=!0):atNextItem||it2.value?(start.push(this.sourceToken),map.items.push({start,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(it2.explicitKey)if(it2.sep)if(it2.value)map.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken(it2.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]});else if(isFlowToken(it2.key)&&!includesToken(it2.sep,"newline")){let start2=getFirstKeyStartProps(it2.start),key=it2.key,sep2=it2.sep;sep2.push(this.sourceToken),delete it2.key,delete it2.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key,sep:sep2}]})}else start.length>0?it2.sep=it2.sep.concat(start,this.sourceToken):it2.sep.push(this.sourceToken);else if(includesToken(it2.start,"newline"))Object.assign(it2,{key:null,sep:[this.sourceToken]});else{let start2=getFirstKeyStartProps(it2.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:start2,key:null,sep:[this.sourceToken]}]})}else it2.sep?it2.value||atNextItem?map.items.push({start,key:null,sep:[this.sourceToken]}):includesToken(it2.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):it2.sep.push(this.sourceToken):Object.assign(it2,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs51=this.flowScalar(this.type);atNextItem||it2.value?(map.items.push({start,key:fs51,sep:[]}),this.onKeyLine=!0):it2.sep?this.stack.push(fs51):(Object.assign(it2,{key:fs51,sep:[]}),this.onKeyLine=!0);return}default:{let bv=this.startBlockValue(map);if(bv){if(bv.type==="block-seq"){if(!it2.explicitKey&&it2.sep&&!includesToken(it2.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else atMapIndent&&map.items.push({start});this.stack.push(bv);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(seq){let it2=seq.items[seq.items.length-1];switch(this.type){case"newline":if(it2.value){let end="end"in it2.value?it2.value.end:void 0;(Array.isArray(end)?end[end.length-1]:void 0)?.type==="comment"?end?.push(this.sourceToken):seq.items.push({start:[this.sourceToken]})}else it2.start.push(this.sourceToken);return;case"space":case"comment":if(it2.value)seq.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(it2.start,seq.indent)){let end=seq.items[seq.items.length-2]?.value?.end;if(Array.isArray(end)){Array.prototype.push.apply(end,it2.start),end.push(this.sourceToken),seq.items.pop();return}}it2.start.push(this.sourceToken)}return;case"anchor":case"tag":if(it2.value||this.indent<=seq.indent)break;it2.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==seq.indent)break;it2.value||includesToken(it2.start,"seq-item-ind")?seq.items.push({start:[this.sourceToken]}):it2.start.push(this.sourceToken);return}if(this.indent>seq.indent){let bv=this.startBlockValue(seq);if(bv){this.stack.push(bv);return}}yield*this.pop(),yield*this.step()}*flowCollection(fc){let it2=fc.items[fc.items.length-1];if(this.type==="flow-error-end"){let top;do yield*this.pop(),top=this.peek(1);while(top?.type==="flow-collection")}else if(fc.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!it2||it2.sep?fc.items.push({start:[this.sourceToken]}):it2.start.push(this.sourceToken);return;case"map-value-ind":!it2||it2.value?fc.items.push({start:[],key:null,sep:[this.sourceToken]}):it2.sep?it2.sep.push(this.sourceToken):Object.assign(it2,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!it2||it2.value?fc.items.push({start:[this.sourceToken]}):it2.sep?it2.sep.push(this.sourceToken):it2.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let fs51=this.flowScalar(this.type);!it2||it2.value?fc.items.push({start:[],key:fs51,sep:[]}):it2.sep?this.stack.push(fs51):Object.assign(it2,{key:fs51,sep:[]});return}case"flow-map-end":case"flow-seq-end":fc.end.push(this.sourceToken);return}let bv=this.startBlockValue(fc);bv?this.stack.push(bv):(yield*this.pop(),yield*this.step())}else{let parent=this.peek(2);if(parent.type==="block-map"&&(this.type==="map-value-ind"&&parent.indent===fc.indent||this.type==="newline"&&!parent.items[parent.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&parent.type!=="flow-collection"){let prev=getPrevProps(parent),start=getFirstKeyStartProps(prev);fixFlowSeqItems(fc);let sep2=fc.end.splice(1,fc.end.length);sep2.push(this.sourceToken);let map={type:"block-map",offset:fc.offset,indent:fc.indent,items:[{start,key:fc,sep:sep2}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=map}else yield*this.lineEnd(fc)}}flowScalar(type){if(this.onNewLine){let nl=this.source.indexOf(`
179
179
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
180
- `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start=getFirstKeyStartProps(prev);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser}});var require_public_api=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer(),Document=require_Document(),errors=require_errors(),log=require_log(),identity2=require_identity(),lineCounter=require_line_counter(),parser=require_parser();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2))),doc}__name(parseDocument,"parseDocument");function parse12(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse12,"parse");function stringify4(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document.Document(value,_replacer,options).toString(options)}__name(stringify4,"stringify");exports2.parse=parse12;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument;exports2.stringify=stringify4}});var require_dist=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit2=require_visit();exports2.Composer=composer.Composer;exports2.Document=Document.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors.YAMLError;exports2.YAMLParseError=errors.YAMLParseError;exports2.YAMLWarning=errors.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import{createHash as createHash2}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash2("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs2 from"node:fs";import{homedir}from"node:os";import path3,{join}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function readReleaseManifest(){try{let raw=fs2.readFileSync(RELEASE_FILE2,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE2,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath2(import.meta.url),CLI_ROOT=path3.resolve(path3.dirname(THIS_FILE),"..",".."),RELEASE_FILE2=path3.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs4 from"node:fs";function ensureCredentialsDir(cfg){fs4.existsSync(cfg.credentialsDir)||fs4.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs4.existsSync(cfg.credentialsFile))return null;let raw=fs4.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs4.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs4.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs4.existsSync(cfg.credentialsFile)&&fs4.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{z as z5}from"zod";function createResponseSchema(dataSchema){return z5.object({data:dataSchema})}function encodeBranchPathSegment(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId,suffix){return`/management/projects/${encodeURIComponent(projectId)}${suffix}`}function managementBranchPath(projectId,branch,suffix){return managementProjectPath(projectId,`/branches/${encodeBranchPathSegment(branch)}${suffix}`)}function tenantPath(projectId,branch,suffix){return`/tenant/${encodeURIComponent(projectId)}/branches/${encodeBranchPathSegment(branch)}${suffix}`}function addQuery(path53,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&&params.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path53}?${queryString}`:path53}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z5.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor))throw new Error("Invalid pagination cursor.");let base64=cursor.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z5.object({items:z5.array(itemSchema),nextCursor:z5.string().nullable(),total:z5.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema,"createResponseSchema");uuidSchema=z5.uuid(),sessionStatusSchema=z5.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z5.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z5.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z5.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z5.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z5.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z5.string().nullable().optional(),goal:z5.string().nullable().optional(),provenance:z5.object({source:z5.enum(["studio","slack","autonomous","mcp"]),creator:z5.object({kind:z5.enum(["user","slack","agent","oauth","conversation"]),id:z5.string()}),conversationId:z5.string().nullable(),runId:z5.string().nullable()}).nullable().optional(),createdBy:z5.string().optional(),createdAt:z5.iso.datetime().optional(),savedRevision:z5.string().nullable().optional(),targetBranch:z5.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z5.string().min(1)}),workingBranch:z5.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z5.url().nullable(),lastActivityAt:z5.iso.datetime(),expiresAt:z5.iso.datetime().nullable(),retention:z5.enum(["temporary","durable"]).optional(),visibility:z5.enum(["internal","user-visible"]).optional(),onExpire:z5.enum(["discard","keep"]),nextOperations:z5.array(z5.string())}),paginationShape={limit:z5.number().int().min(1).max(100).optional(),cursor:z5.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z5.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z5.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor=>cursor==null||/^[1-9]\d*$/.test(cursor)&&Number.isSafeInteger(Number(cursor)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z5.object({data:z5.array(z5.unknown()),meta:z5.object({limit:z5.number().int().positive(),offset:z5.number().int().nonnegative(),total:z5.number().int().nonnegative(),hasMore:z5.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z6}from"zod";function projectAgentSessionsPage(body){let page=body;if(!Array.isArray(page.data))throw new Error("Expected an agent sessions page.");let result=cliAgentSessionsPageSchema.parse({...page,data:page.data.map(value=>{let{env,...session}=value;return{...session,branch:session.branch??env}})});return{...result,items:result.data,nextCursor:result.hasMore?String(result.page+1):null}}function projectAgentStatus(body){let data=recordValue(responseData(body),"Expected an agent session response."),session=recordValue(data.session,"Expected an agent session.");if(!Array.isArray(data.checkpoints))throw new Error("Expected agent session checkpoints.");return agentStatusOutputSchema.parse({data:{session:{...session,branch:session.branch??session.env},checkpoints:data.checkpoints}})}var agentTriggerKindSchema,agentCapabilitySchema,agentListItemSchema,agentListResponseSchema,manualAgentRunResponseSchema,publicAgentSessionSchema,publicAgentCheckpointSchema,agentStatusOutputSchema,cliAgentSessionSchema,cliAgentSessionsPageSchema,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common();agentTriggerKindSchema=z6.enum(["manual","schedule","webhook"]),agentCapabilitySchema=z6.object({token:z6.string().min(1),risk:z6.enum(["low","medium","high","critical"]),description:z6.string()}),agentListItemSchema=z6.object({name:z6.string().min(1),description:z6.string().nullable(),goalFirstLine:z6.string().nullable(),declaredCapabilities:z6.array(agentCapabilitySchema),triggers:z6.array(z6.object({kind:agentTriggerKindSchema,summary:z6.string()})),triggerStates:z6.array(z6.object({triggerIndex:z6.number().int().nonnegative(),triggerKind:agentTriggerKindSchema,enabled:z6.boolean(),wired:z6.boolean(),syncError:z6.string().nullable()})),availability:z6.enum(["available","pending_merge"]),paused:z6.boolean(),nextRunAt:z6.iso.datetime().nullable()}),agentListResponseSchema=createResponseSchema(z6.array(agentListItemSchema)),manualAgentRunResponseSchema=createResponseSchema(z6.union([z6.object({sessionId:z6.string().min(1)}),z6.object({skipped:z6.enum(["no-manual-trigger","agent-not-deployed","agent-config-invalid","manual-trigger-not-synced","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])})])),publicAgentSessionSchema=z6.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,agentName:z6.string().min(1),triggerKind:agentTriggerKindSchema,status:z6.enum(["planned","running","finished","cancelled","errored"]),startedAt:z6.iso.datetime().nullable(),finishedAt:z6.iso.datetime().nullable(),cancelledAt:z6.iso.datetime().nullable(),terminalReason:z6.string().nullable(),errorMessage:z6.string().nullable(),reportDocument:z6.unknown().nullable(),reviewSummary:z6.unknown().nullable(),reviewCaptureError:z6.string().nullable(),createdAt:z6.iso.datetime(),updatedAt:z6.iso.datetime()}),publicAgentCheckpointSchema=z6.object({id:uuidSchema,sessionId:uuidSchema,checkpointIdx:z6.number().int().nonnegative(),payloadSizeBytes:z6.number().int().nonnegative(),checksum:z6.string().length(64),createdAt:z6.iso.datetime()}),agentStatusOutputSchema=createResponseSchema(z6.object({session:publicAgentSessionSchema,checkpoints:z6.array(publicAgentCheckpointSchema)})),cliAgentSessionSchema=z6.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,agentName:z6.string().min(1),triggerKind:agentTriggerKindSchema,status:z6.enum(["planned","running","finished","cancelled","errored"]),startedAt:z6.iso.datetime().nullable(),finishedAt:z6.iso.datetime().nullable(),cancelledAt:z6.iso.datetime().nullable(),costUsd:z6.number().nonnegative().optional(),costCeilingUsd:z6.number().nonnegative(),creditsUsed:z6.number().int().nonnegative().nullable().optional(),terminalReason:z6.string().nullable(),errorMessage:z6.string().nullable(),reportDocument:z6.unknown().nullable(),reviewSummary:z6.unknown().nullable(),reviewCaptureError:z6.string().nullable(),createdAt:z6.iso.datetime(),updatedAt:z6.iso.datetime()}).passthrough(),cliAgentSessionsPageSchema=z6.object({data:z6.array(cliAgentSessionSchema),page:z6.number().int().positive(),limit:z6.number().int().positive().optional(),total:z6.number().int().nonnegative(),totalPages:z6.number().int().nonnegative(),hasMore:z6.boolean()});__name(projectAgentSessionsPage,"projectAgentSessionsPage");__name(projectAgentStatus,"projectAgentStatus");agentsOperations={"agents.list":{domain:"agents",summary:"List site agent bundles, triggers, and activation state from main.",accessScope:"read",effect:"read",inputSchema:z6.object({projectId:uuidSchema}).strict(),outputSchema:agentListResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementBranchPath(projectId,"main","/agents")}),"buildRequest")},"agents.run":{domain:"agents",summary:"Trigger one manual site agent run from main.",accessScope:"agents",effect:"mutation",inputSchema:z6.object({projectId:uuidSchema,agentName:z6.string().min(1).max(120),args:z6.record(z6.string(),z6.unknown()).optional()}).strict(),outputSchema:manualAgentRunResponseSchema,buildRequest:__name(({projectId,agentName,args})=>({method:"POST",path:managementBranchPath(projectId,"main",`/agents/${encodeURIComponent(agentName)}/run`),body:args===void 0?{}:{args}}),"buildRequest")},"agents.status":{domain:"agents",summary:"Read one agent run status, report, and safe checkpoint metadata.",accessScope:"read",effect:"read",inputSchema:z6.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:agentStatusOutputSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/agents/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest"),projectOutput:projectAgentStatus},"agents.runs":{domain:"agents",summary:"List site agent runs with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z6.object({projectId:uuidSchema,agentName:z6.string().min(1).optional(),branch:branchNameSchema.optional(),status:z6.enum(["planned","running","finished","cancelled","errored"]).optional(),...numberedPaginationShape,limit:z6.number().int().min(1).max(200).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:cliAgentSessionsPageSchema.extend({items:z6.array(cliAgentSessionSchema),nextCursor:z6.string().nullable()}),buildRequest:__name(({projectId,agentName,branch,status,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/agents/sessions"),{agent_name:agentName,env:branch,status,page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:projectAgentSessionsPage}}}});import{z as z7}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z7.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z7.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z7.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z7.union([z7.literal(7),z7.literal(30),z7.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z7.object({date:z7.string(),content:z7.string(),updatedAt:z7.string(),updatedByUserId:z7.string()}),analyticsBreakdownSchema=z7.object({key:z7.string(),visitors:z7.number().int().nonnegative(),pageviews:z7.number().int().nonnegative()}),analyticsPageBreakdownSchema=z7.object({path:z7.string(),pageName:z7.string().nullable().optional(),visitors:z7.number().int().nonnegative(),pageviews:z7.number().int().nonnegative()}),analyticsPageviewsSchema=z7.object({range:z7.object({preset:analyticsPresetSchema,requestedFrom:z7.string(),requestedTo:z7.string(),effectiveFrom:z7.string(),effectiveTo:z7.string(),isRetentionLimited:z7.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z7.number().int().nonnegative(),pageviews:z7.number().int().nonnegative(),botPageviews:z7.number().int().nonnegative().default(0),botVisitors:z7.number().int().nonnegative().default(0),bounceRate:z7.number().min(0).max(100),viewsPerVisit:z7.number().nonnegative(),averageVisitDurationSeconds:z7.number().nonnegative(),visitorsSeries:z7.array(z7.object({date:z7.string(),visitors:z7.number().int().nonnegative()})),topPages:z7.array(analyticsPageBreakdownSchema),topBrowsers:z7.array(analyticsBreakdownSchema),topDevices:z7.array(analyticsBreakdownSchema),topBots:z7.array(analyticsBreakdownSchema).default([]),topAiAssistants:z7.array(analyticsBreakdownSchema).default([]),topCountries:z7.array(analyticsBreakdownSchema),topSources:z7.array(analyticsBreakdownSchema),annotations:z7.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z7.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z7.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z7.array(z7.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z7.object({branch:branchNameSchema,annotations:z7.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z7.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z7.object({projectId:uuidSchema,branch:branchNameSchema,date:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z7.string().max(500)}).strict(),outputSchema:z7.union([analyticsAnnotationResponseSchema,z7.null()]),buildRequest:__name(({projectId,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z7.object({projectId:uuidSchema,branch:branchNameSchema,date:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z7.null(),buildRequest:__name(({projectId,branch,date})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z8}from"zod";var assetPathItemSchema,AssetDTOSchema,AssetResponseSchema,AssetReadRequestSchema,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema,GenerateResponseSchema,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common();assetPathItemSchema=z8.object({id:z8.string(),name:z8.string()}),AssetDTOSchema=z8.object({id:z8.string(),name:z8.string(),type:z8.enum(["file","folder"]),originalFileName:z8.string().nullable(),parentId:z8.string().nullable(),mimeType:z8.string().nullable(),fileSize:z8.number().nullable(),url:z8.string().nullable(),storageKey:z8.string().nullable(),slug:z8.string(),tags:z8.array(z8.string()).nullable().optional(),createdAt:z8.string().nullable(),updatedAt:z8.string().nullable(),altText:z8.string().nullable().optional(),caption:z8.string().nullable().optional(),aiCaption:z8.string().nullable().optional(),aiAltText:z8.string().nullable().optional(),aiTags:z8.array(z8.string()).nullable().optional(),aiPrimaryColor:z8.string().nullable().optional(),aiProcessingStatus:z8.string().nullable().optional(),width:z8.number().nullable().optional(),height:z8.number().nullable().optional(),path:z8.array(assetPathItemSchema).optional(),hasChildren:z8.boolean().optional()}),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetReadRequestSchema=z8.object({cursor:z8.string().nullable().optional(),query:z8.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z8.object({url:z8.url(),mediaType:z8.string(),filename:z8.string()}),assetReadBaseSchema=z8.object({assetId:z8.uuid(),filename:z8.string(),mediaType:z8.string(),representation:z8.enum(["text","table","document","archive","image","transcript","video","model"]),content:z8.string(),derivedFiles:z8.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema=z8.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z8.literal("page"),start:z8.number().int().nonnegative(),end:z8.number().int().nonnegative(),total:z8.number().int().nonnegative(),nextCursor:z8.string().nullable(),complete:z8.boolean()}),assetReadBaseSchema.extend({mode:z8.literal("query"),query:z8.string(),source:z8.enum(["original-file","canonical-text","derived-files"]),truncated:z8.boolean()})]),GenerateResponseSchema=createResponseSchema(z8.object({jobId:z8.string(),status:z8.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z8.string().nullable().optional(),credits:z8.number().optional(),costUsd:z8.number().optional(),billingMode:z8.enum(["fimo-credits","provider-account"]).optional(),task:z8.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z8.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema),successMessageResponseSchema=z8.object({data:z8.object({message:z8.literal("success")})}),assetGenerationInputSchema=z8.object({projectId:uuidSchema,branch:branchNameSchema,task:z8.string().min(1).optional(),model:z8.string().min(1).optional(),options:z8.record(z8.string(),z8.unknown()),name:z8.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z8.string().max(2e3).optional(),caption:z8.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z8.object({projectId:uuidSchema,sessionId:uuidSchema,url:z8.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z8.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z8.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z8.string().max(1024).refine(path53=>path53.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path53=>path53.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z8.string().max(2e3).optional(),caption:z8.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z8.string().max(200).optional(),type:z8.enum(["file","folder"]).optional(),mimePrefix:z8.string().max(50).optional(),sortBy:z8.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z8.enum(["asc","desc"]).optional(),includePath:z8.boolean().optional(),excludeHidden:z8.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema(AssetReadResultSchema),buildRequest:__name(({projectId,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema,buildRequest:__name(({projectId,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema}),buildRequest:__name(({projectId,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,name:z8.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema,buildRequest:__name(({projectId,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z8.record(z8.string(),z8.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.record(z8.string(),z8.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z8.record(z8.string(),z8.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.record(z8.string(),z8.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z8.unknown(),buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z8.record(z8.string(),z8.unknown()),buildRequest:__name(({projectId,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.record(z8.string(),z8.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema,buildRequest:__name(({projectId,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z9}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common();creditBalanceOutputSchema=z9.object({projectId:uuidSchema,organizationId:z9.string(),balance:z9.object({totalAvailable:z9.number(),nearLimit:z9.boolean(),canUseAi:z9.boolean(),buckets:z9.object({dailyFreeAvailable:z9.number(),monthlyAvailable:z9.number(),purchasedAvailable:z9.number(),awardedAvailable:z9.number()})}),allowances:z9.object({dailyCredits:z9.object({periodCap:z9.number(),dailyGrant:z9.number(),usedThisPeriod:z9.number(),remainingThisPeriod:z9.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z9.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z10}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z10.object({ok:z10.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z10.array(z10.object({surface:backendSurfaceSchema,count:z10.number().int().nonnegative()})),conflicts:z10.array(backendConflictSchema).optional(),summary:z10.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z10.object({mergeId:uuidSchema,conflicts:z10.array(backendConflictSchema),draftResolutions:z10.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z10.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z10.object({data:z10.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report=z10.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z10.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z10.array(backendSurfaceDeltaSchema).max(6),crossSurface:z10.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report.branch??report.env,against:report.vs,state:report.syncState==="in-sync"?"clean":"changed",syncState:report.syncState,generatedAt:report.generatedAt,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report=z10.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z10.string().min(1),surfaces:z10.array(backendSurfaceDeltaSchema).max(6),crossSurface:z10.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report.fromBranch??report.fromEnv,against:report.toBranch??report.toEnv,generatedAt:report.generatedAt,fingerprint:report.fingerprint,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common();branchSchema=z10.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z10.enum(["provisioning","active","deleted"]),kind:z10.enum(["user","agent-session"]),createdAt:z10.string().optional(),updatedAt:z10.string().optional(),createdBy:z10.string().nullable().optional(),deletedAt:z10.string().nullable().optional()}).passthrough(),branchResponseSchema=z10.object({data:branchSchema}),branchSurfaceStatusSchema=z10.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z10.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z10.iso.datetime(),backendCrossSurfaceFindingSchema=z10.object({id:z10.string(),kind:z10.string(),description:z10.string(),severity:z10.enum(["warning","error"]),source:z10.object({surface:backendSurfaceSchema,key:z10.string()}),target:z10.object({surface:backendSurfaceSchema,key:z10.string()}),actions:z10.array(z10.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z10.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z10.number().int().nonnegative(),conflictCount:z10.number().int().nonnegative(),items:z10.array(z10.object({verb:branchDeltaVerbSchema,key:z10.string(),detail:z10.string().optional(),origin:z10.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z10.record(z10.string(),z10.unknown()).optional()})).max(1e3).optional(),truncated:z10.boolean().optional(),error:z10.string().optional()}),branchSurfaceSummarySchema=z10.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z10.number().int().nonnegative(),conflictCount:z10.number().int().nonnegative(),error:z10.string().optional(),items:z10.array(z10.object({verb:branchDeltaVerbSchema,key:z10.string(),detail:z10.string().optional(),origin:z10.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z10.record(z10.string(),z10.unknown()).optional()})).optional(),truncated:z10.boolean().optional()}),branchStatusOutputSchema=z10.object({branch:branchNameSchema,against:branchNameSchema,state:z10.enum(["clean","changed"]),syncState:z10.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z10.array(branchSurfaceSummarySchema).max(6),crossSurface:z10.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z10.object({verb:branchDeltaVerbSchema,key:z10.string(),detail:z10.string().optional(),meta:z10.record(z10.string(),z10.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z10.string().min(1),surfaces:z10.array(branchSurfaceSummarySchema.extend({truncated:z10.boolean(),items:z10.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z10.object({path:z10.string(),state:z10.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z10.string(),additions:z10.number().int().nonnegative(),deletions:z10.number().int().nonnegative()}),contentSnapshotSchema=z10.object({id:z10.string(),slug:z10.string(),contentType:z10.string(),data:z10.record(z10.string(),z10.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z10.object({collection:z10.string(),rowId:z10.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z10.object({name:z10.string(),label:z10.string(),isSingleton:z10.boolean(),fields:z10.record(z10.string(),z10.unknown())}),schemaDiffOutputSchema=z10.object({typeName:z10.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z10.object({id:z10.string(),name:z10.string(),type:z10.enum(["file","folder"]),mimeType:z10.string().nullable(),storageKey:z10.string().nullable(),url:z10.string().nullable(),fileSize:z10.number().nullable(),width:z10.number().nullable(),height:z10.number().nullable(),altText:z10.string().nullable(),caption:z10.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z10.object({assetId:z10.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z10.object({locale:z10.string(),key:z10.string(),parent:z10.string().nullable(),child:z10.string().nullable()}),formSnapshotSchema=z10.object({formName:z10.string(),label:z10.string().nullable(),schemaFingerprint:z10.string(),fields:z10.record(z10.string(),z10.unknown())}),formDiffOutputSchema=z10.object({formName:z10.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z10.object({surface:backendSurfaceSchema,key:z10.string(),kind:z10.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z10.string(),parentValue:z10.unknown().optional(),childValue:z10.unknown().optional(),conflictingFields:z10.array(z10.string()).optional(),code:z10.object({path:z10.string(),unresolvable:z10.boolean().optional(),reason:z10.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z10.object({field:z10.string(),choice:z10.enum(["parent","child","pick","ai-pick"]),pickedValue:z10.unknown().optional(),aiSessionId:z10.string().optional()}),conflictResolutionSchema=z10.object({surface:branchSurfaceSchema,key:z10.string(),choice:z10.enum(["parent","child","pick"]),pickedValue:z10.unknown().optional(),fieldPicks:z10.array(fieldPickSchema).optional()}),mergeResultSchema=z10.object({ok:z10.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z10.array(z10.object({surface:branchSurfaceSchema,count:z10.number().int().nonnegative()})),conflicts:z10.array(conflictSchema).optional(),summary:z10.string().optional()}),mergeHydrationSchema=z10.object({mergeId:uuidSchema,conflicts:z10.array(conflictSchema),draftResolutions:z10.array(conflictResolutionSchema),status:z10.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z10.object({content:z10.string(),sha:z10.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z10.object({path:z10.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,includeDeleted:z10.boolean().optional(),includeAgentBranches:z10.boolean().optional()}).strict(),outputSchema:z10.object({data:z10.array(branchSchema)}),buildRequest:__name(({projectId,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId,from,name})=>({method:"POST",path:managementProjectPath(projectId,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z10.object({branch:branchSchema,conflicts:z10.number().int().nonnegative()}),buildRequest:__name(({projectId,branch,from})=>({method:"POST",path:managementBranchPath(projectId,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z10.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z10.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z10.unknown(),buildRequest:__name(({projectId,branch})=>({method:"DELETE",path:managementBranchPath(projectId,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z10.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z10.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,path:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId,branch,path:path53,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path53,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,collection:z10.string().min(1),rowId:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,locale:z10.string().min(1),key:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,formName:z10.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z10.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z10.array(conflictResolutionSchema)}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectMergeResult},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z10.object({ok:z10.boolean()}),buildRequest:__name(({projectId,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z10.object({ok:z10.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId,branch,from})=>({method:"GET",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z10.array(conflictResolutionSchema)}).strict(),outputSchema:z10.object({mergeId:uuidSchema,lastEditedAt:z10.string()}),buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z10.object({mergeId:uuidSchema,lastEditedAt:z10.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z10.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId,branch,from,path:path53})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path53})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z11}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common();projectDomainSchema=z11.object({id:z11.string(),hostname:z11.string(),status:z11.string(),ssl:z11.record(z11.string(),z11.unknown()),cnameTarget:z11.string(),apexTargets:z11.array(z11.string()),dnsAutoConfigured:z11.boolean(),createdAt:z11.unknown(),provider:z11.enum(["cloudflare","saas_custom_domains"]),domainType:z11.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z11.object({id:uuidSchema,domain:z11.string(),status:z11.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z11.enum(["fimo","external"]),autoRenew:z11.boolean(),paymentStatus:z11.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z11.string().nullable()}).passthrough(),domainSearchResultSchema=z11.object({domain:z11.string(),available:z11.boolean(),premium:z11.boolean(),price:z11.number().nullable(),renewalPrice:z11.number().nullable(),purchaseType:z11.string().nullable()}).passthrough(),domainPricingSchema=z11.object({domain:z11.string(),price:z11.number().nullable(),renewalPrice:z11.number().nullable(),premium:z11.boolean(),allowedYears:z11.array(z11.number().int().positive())}).passthrough(),projectPath=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z11.object({}).strict(),outputSchema:z11.object({domainPurchaseEnabled:z11.boolean(),publicationDomain:z11.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,slug:z11.string().min(1).max(63)}).strict(),outputSchema:z11.object({subdomain:z11.string(),subdomainUpdatedAt:z11.string()}),buildRequest:__name(({projectId,slug})=>({method:"PATCH",path:projectPath(projectId,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z11.object({projectId:uuidSchema,base:z11.string().min(1).max(63).optional(),max:z11.number().int().positive().optional()}).strict(),outputSchema:z11.array(z11.string()),buildRequest:__name(({projectId,base,max})=>({method:"GET",path:addQuery(projectPath(projectId,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z11.object({data:z11.object({suggestions:z11.array(z11.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z11.object({projectId:uuidSchema}).strict(),outputSchema:z11.array(projectDomainSchema),buildRequest:__name(({projectId})=>({method:"GET",path:projectPath(projectId,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,hostname:z11.string().min(1).max(255),redirectToWww:z11.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,domainId:z11.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,domainId})=>({method:"POST",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,domainId:z11.string().min(1)}).strict(),outputSchema:z11.unknown(),buildRequest:__name(({projectId,domainId})=>({method:"DELETE",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z11.object({keyword:z11.string().min(1).max(100),tldFilter:z11.array(z11.string().min(1)).optional()}).strict(),outputSchema:z11.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z11.object({domain:z11.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z11.object({organizationId:z11.string().min(1)}).strict(),outputSchema:z11.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z11.object({organizationId:z11.string().min(1),domain:z11.string().min(1).max(255),years:z11.number().int().min(1).max(10).optional(),autoRenew:z11.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z11.object({organizationId:z11.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z12}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema.parse(body))}var EntryDTOSchema,PaginatedEntriesDTOSchema,EntryResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,BulkCreateEntriesResponseSchema,BulkUpdateEntriesResponseSchema,BulkDeleteEntriesResponseSchema,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common();EntryDTOSchema=z12.object({id:z12.string(),entryId:z12.string(),documentId:z12.string(),slug:z12.string(),locale:z12.string().optional(),createdAt:z12.string(),updatedAt:z12.string(),__fimo:z12.object({contentType:z12.string()})}).passthrough(),PaginatedEntriesDTOSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({limit:z12.number(),offset:z12.number(),total:z12.number(),hasMore:z12.boolean()})}),EntryResponseSchema=createResponseSchema(EntryDTOSchema),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z12.union([z12.string(),z12.number(),z12.boolean(),z12.null()]),entryWhereOperatorSchema=z12.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z12.array(entryWhereScalarSchema).optional(),$nin:z12.array(entryWhereScalarSchema).optional(),$contains:z12.string().optional(),$startsWith:z12.string().optional(),$null:z12.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z12.record(z12.string(),z12.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z12.record(z12.string(),z12.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z12.object({data:z12.record(z12.string(),z12.unknown()),locale:z12.string().min(1).optional(),documentId:z12.uuid().optional()}),BulkCreateEntriesResponseSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({created:z12.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({updated:z12.number().int().nonnegative(),missing:z12.array(z12.string())})}),BulkDeleteEntriesResponseSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({deleted:z12.number().int().nonnegative(),missing:z12.array(z12.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema),typeNameSchema=z12.string().min(1).max(255),localeSchema=z12.string().min(1),populateSchema=z12.array(z12.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema.shape.data,entryResponseSchema=EntryResponseSchema,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z12.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,search:z12.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z12.string().min(1).max(255),data:entryDataSchema,locale:z12.string().min(1).optional(),documentId:z12.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z12.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z12.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z12.record(z12.string(),z12.unknown())}).strict(),outputSchema:z12.unknown(),buildRequest:__name(({projectId,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z12.object({data:z12.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,sql:z12.string().min(1)}).strict(),outputSchema:z12.object({data:z12.array(z12.record(z12.string(),z12.unknown())),meta:z12.object({rowCount:z12.number().int().nonnegative(),truncated:z12.boolean()})}),buildRequest:__name(({projectId,branch,sql})=>({method:"POST",path:tenantPath(projectId,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z12.array(z12.unknown()).max(MAX_BULK_ENTRIES)}).strict(),outputSchema:BulkCreateEntriesResponseSchema,buildRequest:__name(({projectId,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z12.union([z12.object({ids:z12.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES)}),z12.object({where:EntryWhereSchema}),z12.object({updates:z12.array(z12.object({id:uuidSchema,body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema,buildRequest:__name(({projectId,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z12.union([z12.object({ids:z12.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES)}),z12.object({where:EntryWhereSchema})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema,buildRequest:__name(({projectId,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z13}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common();productionEnvironmentSchema=z13.object({id:z13.literal("production"),projectId:uuidSchema,name:z13.string(),kind:z13.literal("production"),sourceBranch:z13.string().min(1),isPublished:z13.boolean(),url:z13.string().nullable()}),previewEnvironmentSchema=z13.object({id:z13.literal("preview"),projectId:uuidSchema,name:z13.string(),kind:z13.literal("preview"),matchedBranchCount:z13.number().int().nonnegative()}),customEnvironmentSchema=z13.object({id:uuidSchema,projectId:uuidSchema,name:z13.string().min(1).max(64),branchPatterns:z13.array(z13.string().min(1).max(255)).min(1),description:z13.string().max(255).nullable(),kind:z13.literal("custom"),matchedBranchCount:z13.number().int().nonnegative()}),environmentSchema=z13.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z13.string().trim().min(1).max(64),branchPatterns:z13.array(z13.string().min(1).max(255)).min(1),description:z13.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z13.object({projectId:uuidSchema}).strict(),outputSchema:z13.array(environmentSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/environments")}),"buildRequest"),projectOutput:__name(body=>z13.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z13.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z13.object({projectId:uuidSchema,environmentId:z13.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z13.object({projectId:uuidSchema,environmentId:z13.string().min(1)}).strict(),outputSchema:z13.object({deletedId:uuidSchema}),buildRequest:__name(({projectId,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z13.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z14}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common();fileReadOutputSchema=z14.object({data:z14.object({path:z14.string(),content:z14.string(),totalLines:z14.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z14.object({data:z14.object({paths:z14.array(z14.string().min(1)).max(2e3),truncated:z14.boolean()})}),fileGrepOutputSchema=z14.object({data:z14.object({matches:z14.array(z14.object({path:z14.string().min(1),line:z14.number().int().positive(),text:z14.string()})).max(200),truncated:z14.boolean()})}),fileWriteInputSchema=z14.object({projectId:uuidSchema,sessionId:uuidSchema,path:z14.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte write limit.`),overwrite:z14.boolean().optional()}).strict(),fileEditInputSchema=z14.object({projectId:uuidSchema,sessionId:uuidSchema,path:z14.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte edit limit.`),replaceAll:z14.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z14.object({path:z14.string(),created:z14.boolean(),tip:z14.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z14.object({projectId:uuidSchema,sessionId:uuidSchema,files:z14.array(z14.object({path:z14.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files=>files.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z14.array(z14.object({path:z14.string(),created:z14.boolean()}).passthrough()),tip:z14.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z14.object({path:z14.string(),replacements:z14.number().int().nonnegative(),tip:z14.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z14.object({path:z14.string(),deleted:z14.literal(!0),tip:z14.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z14.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z14.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId,branch,sessionId,path:path53})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path53})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z14.object({...fileSearchInputShape,pattern:z14.string().min(1).max(300).optional(),limit:z14.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z14.object({...fileSearchInputShape,pattern:z14.string().min(1).max(200),include:z14.string().min(1).max(300).optional(),caseInsensitive:z14.boolean().optional(),maxMatches:z14.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path53,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path53,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId,sessionId,files})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId,sessionId,path:path53,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path53,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z14.object({projectId:uuidSchema,sessionId:uuidSchema,path:z14.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path53})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path53}}),"buildRequest")}}}});import{z as z15}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z15.object({data:z15.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z15.object({data:z15.array(formSubmissionSchema),total:z15.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page.data.length===0&&offset<page.total)throw new Error("Expected a page that advances the cursor.");return{items:page.data,nextCursor:offset+page.data.length<page.total?encodePaginationCursor(offset+page.data.length):null,total:page.total}}var formFieldSchema,FormContentSchema,FormUpdateSchema,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common();formFieldSchema=z15.object({type:z15.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z15.string(),placeholder:z15.string().optional(),required:z15.boolean().optional(),defaultValue:z15.string().optional(),options:z15.array(z15.string()).optional(),validation:z15.object({minLength:z15.number().optional(),maxLength:z15.number().optional(),min:z15.number().optional(),max:z15.number().optional(),pattern:z15.string().optional(),maxFileSize:z15.number().optional(),accept:z15.array(z15.string()).optional()}).optional()}),FormContentSchema=z15.object({name:z15.string().min(1).max(255),label:z15.string().min(1).max(255),fields:z15.record(z15.string(),formFieldSchema)}).strict(),FormUpdateSchema=FormContentSchema.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."}),rawFormSchema=z15.object({id:uuidSchema,name:FormContentSchema.shape.name,label:FormContentSchema.shape.label,fields:FormContentSchema.shape.fields,settings:z15.record(z15.string(),z15.unknown()).nullable().optional(),createdAt:z15.string(),updatedAt:z15.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z15.object({data:formSchema}),formSubmissionSchema=z15.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z15.record(z15.string(),z15.unknown()),submittedAt:z15.string()}),formSubmissionResponseSchema=z15.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z15.object({data:z15.object({total:z15.number().int().nonnegative(),dailyCounts:z15.array(z15.object({date:z15.string(),count:z15.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z15.array(formSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),...FormContentSchema.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue of update.error.issues)context.addIssue({...issue,path:issue.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),...paginationShape,searchQuery:z15.string().max(200).optional(),sortDirection:z15.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),submissionId:z15.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),submissionId:z15.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z16}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common();estimateSchema=z16.object({costUsd:z16.number(),credits:z16.number().optional(),billingMode:z16.enum(["fimo-credits","provider-account"]).optional(),confidence:z16.enum(["exact","estimated","metered"]),basis:z16.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z16.object({projectId:uuidSchema,model:z16.string().min(1),options:z16.record(z16.string(),z16.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z16.object({projectId:uuidSchema,branch:branchNameSchema,task:z16.string().min(1),options:z16.record(z16.string(),z16.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,branch,task,options})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z17}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common();historyKindSchema=z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z17.object({versionId:uuidSchema,commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:historyKindSchema,createdAt:z17.iso.datetime(),expiresAt:z17.iso.datetime()}),projectVersionPageSchema=z17.object({items:z17.array(projectVersionSchema),nextCursor:z17.string().nullable()}),historySummarySchema=z17.object({usage:z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),retentionDays:z17.number().int().positive()}),restoreResultSchema=z17.object({durationMs:z17.number().nonnegative().optional(),warning:z17.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,limit:z17.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/versions"),{limit,cursor})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,name:z17.string().min(1),description:z17.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z18}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page.items.map(publicationRecord),nextCursor:page.nextCursor,retention:page.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z18.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z18.object({isPublished:z18.boolean(),publishedAt:z18.iso.datetime().nullable(),publishedVersion:z18.string().nullable()}),publicationOutputSchema=z18.object({id:uuidSchema,status:z18.enum(["queued","building","published","failed","canceled"]),label:z18.string().nullable(),notes:z18.string().nullable(),source:z18.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z18.string().nullable(),framework:z18.string().nullable(),commit:z18.string().nullable()}),createdAt:z18.iso.datetime(),finishedAt:z18.iso.datetime().nullable(),url:z18.string().nullable(),failureCode:z18.string().nullable()}),publicationsPageOutputSchema=z18.object({items:z18.array(publicationOutputSchema),nextCursor:z18.string().nullable(),retention:z18.object({scope:z18.literal("publication_attempt_record"),records:z18.literal("project_lifetime")})}),publicationLogsOutputSchema=z18.object({status:z18.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z18.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z18.string().nullable(),items:z18.array(z18.object({timestamp:z18.iso.datetime(),phase:z18.enum(["build","deploy"]),stream:z18.enum(["command","stdout","stderr","status","error"]),message:z18.string()}))}),sandboxLogsOutputSchema=z18.object({status:z18.enum(["ok","unavailable"]),reason:z18.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z18.string().nullable(),items:z18.array(z18.object({id:z18.string(),timestamp:z18.iso.datetime().nullable(),source:z18.enum(["install","dev-server"]),phase:z18.string(),stream:z18.enum(["combined","stdout","stderr"]),message:z18.string()})),nextCursor:z18.string().nullable(),retention:z18.object({scope:z18.literal("sandbox_process_snapshot"),timestamps:z18.literal("process_start"),droppedOldest:z18.boolean(),phases:z18.array(z18.object({phase:z18.string(),source:z18.enum(["install","dev-server"]),status:z18.string(),startedAt:z18.iso.datetime().nullable(),exitCode:z18.number().int().nullable(),events:z18.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z18.object({url:z18.string(),branch:branchNameSchema}),previewOpenOutputSchema=z18.object({url:z18.url(),expiresAt:z18.iso.datetime().nullable()}),publishOutputSchema=z18.object({success:z18.boolean(),message:z18.string().optional(),firstPublish:z18.boolean(),publicationId:z18.string().optional(),url:z18.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,limit:z18.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,publicationId:z18.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId,publicationId})=>({method:"GET",path:managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z18.object({projectId:uuidSchema,label:z18.string().trim().min(1).max(120).optional(),notes:z18.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId,label,notes})=>({method:"POST",path:managementProjectPath(projectId,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,publicationId:z18.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/sandbox/logs"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z18.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z19}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common();knowledgeSchema=z19.object({content:z19.string(),updatedAt:z19.string().nullable(),updatedBy:z19.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z19.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance.",accessScope:"write",effect:"mutation",inputSchema:z19.object({projectId:uuidSchema,content:z19.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId,content:content2})=>({method:"PUT",path:managementProjectPath(projectId,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z20}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common();init_entries();TranslationDTOSchema=z20.object({key:z20.string(),value:z20.string().optional(),defaultValue:z20.string(),locale:z20.string()}),labelResponseSchema=createResponseSchema(TranslationDTOSchema),labelListOutputSchema=z20.object({data:z20.array(z20.union([TranslationDTOSchema,z20.object({key:z20.string(),values:z20.record(z20.string(),z20.string())})]))}),labelUpsertOutputSchema=z20.object({created:z20.number().int().nonnegative(),updated:z20.number().int().nonnegative(),deleted:z20.number().int().nonnegative(),defaultLocale:z20.string(),locales:z20.array(z20.string())}),labelDeleteOutputSchema=z20.object({key:z20.string(),locale:z20.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z20.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"GET",path:tenantPath(projectId,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,key:z20.string(),value:z20.string(),locale:z20.string().optional()}).strict(),outputSchema:TranslationDTOSchema,buildRequest:__name(({projectId,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,records:z20.array(z20.object({key:z20.string(),value:z20.string(),locale:z20.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId,branch,records})=>({method:"POST",path:tenantPath(projectId,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,locale:z20.string().optional(),key:z20.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z21}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleResponseSchema,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common();projectLocaleCoverageSchema=z21.object({translated:z21.number().int().nonnegative(),total:z21.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema=createResponseSchema(z21.object({defaultLocale:z21.string(),locales:z21.array(z21.object({locale:z21.string(),isDefault:z21.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z21.string().min(1).max(40),ProjectLocaleMutationResponseSchema=createResponseSchema(z21.object({locale:z21.string()})),RemoveProjectLocaleResponseSchema=createResponseSchema(z21.object({locale:z21.string(),entriesDeleted:z21.number().int().nonnegative(),labelsDeleted:z21.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"POST",path:managementBranchPath(projectId,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z22}from"zod";var agentQuestionSchema,projectPath2,notificationsOperations,init_notifications=__esm({"../../packages/sdk/dist/operations/notifications.js"(){"use strict";init_common();agentQuestionSchema=z22.object({id:uuidSchema,projectId:uuidSchema,threadId:uuidSchema,invocationId:uuidSchema,agentKey:z22.string(),anchorEnv:z22.string(),retainedEnv:z22.string(),state:z22.enum(["open","answered","expired","cancelled","superseded"]),request:z22.record(z22.string(),z22.unknown()),answer:z22.unknown().nullable(),askedAt:z22.iso.datetime(),expiresAt:z22.iso.datetime(),closedAt:z22.iso.datetime().nullable()}).passthrough(),projectPath2=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),notificationsOperations={"questions.get":{domain:"notifications",summary:"Read the decision form attached to an agent question.",accessScope:"read",effect:"read",inputSchema:z22.object({projectId:uuidSchema,questionId:uuidSchema}).strict(),outputSchema:agentQuestionSchema,buildRequest:__name(({projectId,questionId})=>({method:"GET",path:projectPath2(projectId,`/questions/${encodeURIComponent(questionId)}`)}),"buildRequest"),projectOutput:responseData},"questions.answer":{domain:"notifications",summary:"Answer an agent question and continue its retained run.",accessScope:"write",effect:"mutation",inputSchema:z22.object({projectId:uuidSchema,questionId:uuidSchema,answer:z22.record(z22.string(),z22.unknown())}).strict(),outputSchema:z22.object({question:agentQuestionSchema,continuationInvocationId:uuidSchema,deduped:z22.boolean()}),buildRequest:__name(({projectId,questionId,answer})=>({method:"POST",path:projectPath2(projectId,`/questions/${encodeURIComponent(questionId)}/answer`),body:answer}),"buildRequest"),projectOutput:responseData}}}});import{z as z23}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common();organizationSchema=z23.object({id:z23.string().min(1),name:z23.string(),slug:z23.string()}),organizationMemberSchema=z23.object({id:z23.string().min(1),role:z23.string(),createdAt:z23.string().optional(),user:z23.object({id:z23.string().min(1),name:z23.string().nullable().optional(),email:z23.string().nullable().optional()}).optional()}),organizationInvitationSchema=z23.object({id:z23.string().min(1),email:z23.email(),role:z23.string(),organizationId:z23.string().min(1),inviterId:z23.string().min(1),status:z23.string(),expiresAt:z23.string(),createdAt:z23.string()}).passthrough(),referralSummarySchema=z23.object({counts:z23.object({signed_up:z23.number().int(),activated:z23.number().int()}),credits:z23.object({total:z23.number().int(),earned:z23.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z23.object({}).strict(),outputSchema:createResponseSchema(z23.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z23.object({organizationId:z23.string().min(1)}).strict(),outputSchema:z23.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z23.object({members:z23.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z23.object({organizationId:z23.string().min(1),email:z23.email(),role:z23.enum(["owner","admin","member"]),resend:z23.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z23.object({userId:z23.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z24}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common();projectSchema=z24.object({id:uuidSchema,name:z24.string(),displayName:z24.string().nullable(),organizationId:z24.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z24.string().optional(),appUrl:z24.string().nullable().optional(),previewEnabled:z24.boolean().optional()}).passthrough(),projectResponseSchema=z24.object({data:projectSchema}),transferResultSchema=z24.object({projectId:z24.string(),sourceOrganizationId:z24.string(),targetOrganizationId:z24.string(),movedThreads:z24.number().int().nonnegative(),revokedInvites:z24.number().int().nonnegative(),revokedGrants:z24.number().int().nonnegative(),preservedGrants:z24.number().int().nonnegative(),warnings:z24.array(z24.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z24.object({organizationId:z24.string().min(1).optional()}).strict(),outputSchema:z24.object({data:z24.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z24.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z24.object({organizationId:z24.string().min(1),displayName:z24.string().min(1).optional(),origin:z24.enum(["scratch","migration"]).optional(),starter:z24.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,targetOrganizationId:z24.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,email:z24.email(),role:z24.enum(["full","edit","comment","view"])}).strict(),outputSchema:z24.object({id:z24.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z24.object({id:z24.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema}).strict(),outputSchema:z24.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z25}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common();dateSchema=z25.iso.datetime(),scheduleStatusSchema=z25.enum(["ok","failed"]),runStatusSchema=z25.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z25.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z25.string().min(1),name:z25.string().min(1),cron:z25.string().min(1),command:z25.string().min(1),secretKeys:z25.array(z25.string().min(1)),enabled:z25.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z25.string().nullable(),overPolicyReasons:z25.array(z25.string()).optional()}).passthrough(),usageSchema=z25.object({runCount:z25.number().int().nonnegative(),runsWithOutput:z25.number().int().nonnegative()}),policySchema=z25.object({maxRuns:z25.number().int().positive(),retentionDays:z25.number().int().positive().nullable(),outputRetentionDays:z25.number().int().positive(),maxOutputBytes:z25.number().int().positive()}).passthrough(),planSchema=z25.object({code:z25.enum(["Free","PAYG","Premium","Pro"]),source:z25.enum(["cached_subscription","free_fallback"]),activeSchedules:z25.object({used:z25.number().int().nonnegative(),limit:z25.number().int().positive()}),minCadenceMinutes:z25.number().int().positive(),maxRunMs:z25.number().int().positive(),concurrency:z25.object({used:z25.number().int().nonnegative(),limit:z25.number().int().positive()}),compute:z25.object({settledMs:z25.number().int().nonnegative(),activeMs:z25.number().int().nonnegative(),reservedMs:z25.number().int().nonnegative().optional(),includedMs:z25.number().int().positive(),remainingMs:z25.number().int().nonnegative(),resetsAt:dateSchema}),state:z25.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z25.array(z25.string())}).passthrough(),runSchema=z25.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z25.string().min(1),scheduleName:z25.string().min(1),command:z25.string().min(1),status:runStatusSchema,trigger:z25.enum(["cron","ui","cli"]),triggeredBy:z25.object({id:z25.string().min(1),name:z25.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z25.number().int().nullable(),errorCode:z25.string().nullable(),error:z25.string().nullable(),outputBytes:z25.number().int().nonnegative(),outputTruncated:z25.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z25.string().nullable(),secretSnapshot:z25.object({state:z25.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z25.array(z25.object({key:z25.string().min(1),updatedAt:dateSchema.nullable(),resolution:z25.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z25.object({items:z25.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z25.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z25.object({items:z25.array(runSchema),nextCursor:z25.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z25.string().min(1).max(120),cron:z25.string().min(1).max(120),command:z25.string().min(1).max(500),secretKeys:z25.array(z25.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape}).strict(),outputSchema:z25.array(scheduleSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z25.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,...scheduleWriteShape,enabled:z25.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z25.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z25.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z25.object({ok:z25.literal(!0)}),buildRequest:__name(({projectId,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z25.object({ok:z25.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z26}from"zod";function projectSchemaDefinition(body){return z26.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common();contentTypeSchema=z26.object({id:z26.string(),name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),slugUnique:z26.boolean(),i18n:z26.record(z26.string(),z26.unknown()),groups:z26.array(z26.record(z26.string(),z26.unknown())),fields:z26.record(z26.string(),z26.unknown()),createdAt:z26.string(),updatedAt:z26.string()}).passthrough(),schemaListOutputSchema=z26.object({contentTypes:z26.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z26.object({typeName:z26.string().min(1).max(255),generatedPaths:z26.array(z26.string().min(1)).max(1e3),tip:z26.string().min(1)})}),schemaDefinitionInputSchema=z26.record(z26.string(),z26.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z26.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId,branch,typeName})=>({method:"GET",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z26.array(schemaDefinitionInputSchema).min(1).max(100),operations:z26.array(z26.record(z26.string(),z26.unknown())).optional()}).strict(),outputSchema:z26.array(z26.unknown()),buildRequest:__name(({projectId,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z26.object({data:z26.array(z26.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z26.string().min(1).max(255)}).strict(),outputSchema:z26.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z26.object({data:z26.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z26.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z26.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z26.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z26.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z27}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common();environmentSchema2=z27.union([z27.literal("production"),z27.literal("preview"),uuidSchema]),secretKindSchema=z27.enum(["variable","secret"]),projectSecretSchema=z27.object({id:z27.string().min(1),projectId:z27.string().min(1),key:z27.string().min(1),kind:secretKindSchema,exposure:z27.enum(["public","private"]),environment:environmentSchema2,value:z27.string().optional(),maskedValue:z27.string().optional(),createdAt:z27.string(),updatedAt:z27.string()}),secretWriteInputSchema=z27.object({projectId:uuidSchema,key:z27.string().min(1).max(255),kind:secretKindSchema,value:z27.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z27.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z27.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z27.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z27.object({projectId:uuidSchema,key:z27.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z27.unknown(),buildRequest:__name(({projectId,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z27.object({projectId:uuidSchema,branch:z27.string().min(1)}).strict(),outputSchema:z27.object({branch:z27.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z27.array(z27.object({branch:z27.string().optional(),env:z27.string().optional(),parentBranch:z27.string().nullable().optional(),parentEnv:z27.string().nullable().optional(),resolvedEnvironment:z27.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z28}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,resolvedMergeStrategySchema,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z28.object({status:z28.literal("passed")}).passthrough(),sessionConflictSummarySchema=z28.object({surface:surfaceNameSchema,key:z28.string().min(1),kind:z28.string().optional(),description:z28.string(),path:z28.string().optional()}).passthrough(),surfaceDeltaItemSchema=z28.object({verb:z28.enum(["added","removed","changed","conflict"]),key:z28.string(),detail:z28.string().optional(),origin:z28.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z28.record(z28.string(),z28.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z28.object({surface:surfaceNameSchema,status:z28.enum(["ok","timed_out","failed","unchanged"]),durationMs:z28.number().int().nonnegative().optional(),changedCount:z28.number().int().nonnegative(),conflictCount:z28.number().int().nonnegative(),items:z28.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z28.boolean().optional(),error:z28.string().optional()}).passthrough(),sessionChangesSchema=z28.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z28.iso.datetime(),surfaces:z28.array(perSurfaceDeltaSchema),crossSurface:z28.array(crossSurfaceFindingSchema).optional(),fingerprint:z28.string()}).passthrough(),projectScriptStatusSchema=z28.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z28.discriminatedUnion("operation",[z28.object({operation:z28.literal("dependencies_install"),repairedInstallPolicy:z28.boolean(),tip:z28.string()}),z28.object({operation:z28.literal("schemas_sync"),tip:z28.string()}),z28.object({operation:z28.literal("typecheck"),status:projectScriptStatusSchema,output:z28.string()}),z28.object({operation:z28.literal("lint"),status:projectScriptStatusSchema,output:z28.string()})]),conflictSchema2=z28.object({surface:surfaceNameSchema,key:z28.string(),kind:z28.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z28.string(),parentValue:z28.unknown().optional(),childValue:z28.unknown().optional(),conflictingFields:z28.array(z28.string()).optional(),code:z28.object({path:z28.string(),unresolvable:z28.boolean().optional(),reason:z28.string().optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z28.object({oid:z28.string().optional(),content:z28.string().optional(),truncated:z28.boolean(),binary:z28.boolean()}),codeConflictDetailSchema=z28.object({path:z28.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z28.string(),targetTipSha:z28.string(),mergeBaseSha:z28.string().optional()}),resolutionChoiceSchema=z28.enum(["parent","child","pick"]),conflictResolutionSchema2=z28.object({surface:surfaceNameSchema,key:z28.string().min(1),choice:resolutionChoiceSchema,pickedValue:z28.unknown().optional(),fieldPicks:z28.array(z28.object({field:z28.string().min(1),choice:resolutionChoiceSchema,pickedValue:z28.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),resolvedMergeStrategySchema=z28.object({engine:z28.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z28.enum(["ff_only","ff_prefer","merge"]),squash:z28.boolean()}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z28.string().trim().min(1).max(120).optional(),goal:z28.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z28.object({session:sessionEnvelopeSchema,adopted:z28.boolean()}),buildRequest:__name(({projectId,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z28.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z28.number().int().min(1).max(100).optional()}).strict(),outputSchema:z28.object({items:z28.array(sessionEnvelopeSchema),nextCursor:z28.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z28.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z28.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z28.object({requested:z28.literal(!0),alreadyRequested:z28.boolean(),reviewId:uuidSchema,reviewUrl:z28.url(),status:z28.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z28.string().min(1),savedRevision:z28.string().min(1),fingerprint:z28.string().min(1),visibility:z28.literal("user-visible"),retention:z28.literal("durable"),expiresAt:z28.null(),merged:z28.literal(!1),published:z28.literal(!1),links:z28.object({preview:z28.url(),changes:z28.url(),conversation:z28.url().nullable()})}),buildRequest:__name(({projectId,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z28.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z28.literal("temporary"),visibility:z28.enum(["internal","user-visible"]),expiresAt:z28.iso.datetime()}),buildRequest:__name(({projectId,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId,sessionId})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z28.string().min(1).max(100),args:z28.record(z28.string(),z28.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,action:z28.enum(["merge","discard"]),message:z28.string().max(1e3).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z28.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z28.boolean(),mergeId:uuidSchema.optional(),conflictCount:z28.number().int().nonnegative().optional(),conflicts:z28.array(sessionConflictSummarySchema).optional(),parentAdvanced:z28.boolean().optional(),code:z28.string().optional(),summary:z28.string().nullable().optional()}),buildRequest:__name(({projectId,sessionId,action,message})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z28.number().int().min(1).max(100).optional(),codePath:z28.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z28.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z28.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z28.number().int().nonnegative(),error:z28.string().nullable()}),conflicts:z28.array(conflictSchema2).max(100),nextCursor:z28.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z28.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z28.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z28.iso.datetime()}),buildRequest:__name(({projectId,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z29}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z29.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z29.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z30}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common();supportReportInputSchema=z30.object({message:z30.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z30.object({id:uuidSchema,deliveryStatus:z30.enum(["pending","delivered","failed"]),message:z30.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z30.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z31}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common();jsonObjectSchema=z31.record(z31.string(),z31.unknown()),deliveryStatusSchema=z31.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z31.object({id:uuidSchema,projectId:uuidSchema,name:z31.string(),eventType:z31.string().min(1),enabled:z31.boolean(),destination:z31.object({host:z31.string(),maskedUrl:z31.string(),kind:z31.string()}),filter:jsonObjectSchema,headers:z31.array(jsonObjectSchema),bodyTemplate:z31.unknown().nullable(),signingEnabled:z31.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z31.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z31.string().min(1),status:deliveryStatusSchema,attemptCount:z31.number().int().nonnegative(),responseStatus:z31.number().int().nullable(),createdAt:z31.iso.datetime()}).passthrough(),attemptSchema=z31.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z31.number().int().positive(),status:z31.enum(["delivering","succeeded","failed"]),createdAt:z31.iso.datetime()}).passthrough(),deliveriesPageSchema=z31.object({items:z31.array(deliverySchema),pagination:z31.object({page:z31.number().int().positive(),limit:z31.number().int().positive(),total:z31.number().int().nonnegative(),totalPages:z31.number().int().positive(),hasMore:z31.boolean()}),stats:z31.object({total:z31.number().int().nonnegative(),succeeded:z31.number().int().nonnegative(),failed:z31.number().int().nonnegative()})}),eventSchema=z31.object({type:z31.string().min(1),family:z31.string(),description:z31.string(),variables:z31.array(z31.string()),data:z31.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema}).strict(),outputSchema:z31.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z31.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema}).strict(),outputSchema:z31.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z31.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z31.object({webhook:webhookSchema,signingSecret:z31.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z31.object({webhook:webhookSchema,signingSecret:z31.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z31.unknown(),buildRequest:__name(({projectId,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z31.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z31.object({signingSecret:z31.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z31.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z31.string().nullable()}),buildRequest:__name(({projectId,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z31.object({delivery:deliverySchema,attempts:z31.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z31.object({delivery:deliverySchema,attempts:z31.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z32}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_knowledge();init_labels();init_locales();init_notifications();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...notificationsOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...agentsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z32.object({id:z32.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z32.string().min(1),summary:z32.string().min(1),accessScope:z32.enum(["read","write","code","agents"]),effect:z32.enum(["read","mutation"]),inputJsonSchema:z32.record(z32.string(),z32.unknown()),outputJsonSchema:z32.record(z32.string(),z32.unknown())}).strict(),fimoOperationManifestSchema=z32.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z32.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z32.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client();init_operations()}});import{spawnSync}from"node:child_process";import fs5 from"node:fs";import path5 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs5.existsSync(path5.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile7=defaultReadFile){try{return JSON.parse(readFile7(path5.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs5.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path5.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs5.realpathSync(input)}catch{return path5.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs5.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs5.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs5.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs5.readFileSync(path5.join(root,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path5.join(loadConfig().configDir,"auto-upgrade.lock");try{fs5.mkdirSync(path5.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs5.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs6 from"node:fs";import path6 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function getCliVersion(){try{let raw=fs6.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath3(import.meta.url),CLI_ROOT2=path6.resolve(path6.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path6.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path53,message}=issue;return`${Array.isArray(path53)&&path53.length>0?`${path53.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatError(status,text,body){if(!text)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text}async function parseError(response){let text=await response.text(),body;try{body=text?JSON.parse(text):void 0}catch{return{detail:formatError(response.status,text)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text,body),code:code2,body}}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={};try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message)}catch{}throw new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=process.env.FIMO_API_TOKEN?.trim()||requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path53,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path53}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path53,init={},options={}){let response=await send(path53,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path53,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path53,init={}){let response=await send(path53,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new Error(`API ${init.method??"GET"} ${path53} failed: ${response.status} ${error.detail}`)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path53,status,detail,code2,body){super(`API ${method} ${path53} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path53,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;constructor(apiUrl,required=[],message,server={}){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required,this.code=server.code,this.detail=server.detail}},CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});function colorEnabled(opts={}){if(opts.forceDisable)return!1;let env=opts.env??process.env;return env.NO_COLOR&&env.NO_COLOR.length>0?!1:env.FORCE_COLOR&&env.FORCE_COLOR!=="0"&&env.FORCE_COLOR!=="false"?!0:(opts.isTTY??process.stdout.isTTY??!1)===!0}function makeColorPalette(opts={}){let on=colorEnabled(opts),wrap=__name(style=>s=>on?`${ANSI[style]}${s}${ANSI.reset}`:s,"wrap");return{enabled:on,bold:wrap("bold"),dim:wrap("dim"),red:wrap("red"),green:wrap("green"),yellow:wrap("yellow"),blue:wrap("blue"),magenta:wrap("magenta"),cyan:wrap("cyan"),gray:wrap("gray")}}var ANSI,palette,init_color=__esm({"src/cli/utils/format/color.ts"(){ANSI={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};__name(colorEnabled,"colorEnabled");__name(makeColorPalette,"makeColorPalette");palette=makeColorPalette()}});function detectProjectLayout(paths){let hasCurrentProject=!1,hasLegacyProject=!1,hasCurrentMarker=!1,hasLegacyMarker=!1;for(let input of paths){let file=input.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");hasCurrentProject||=file===CURRENT_PROJECT_LAYOUT.project,hasLegacyProject||=file===LEGACY_PROJECT_LAYOUT.project,hasCurrentMarker||=file===CURRENT_PROJECT_LAYOUT.config||file===CURRENT_PROJECT_LAYOUT.agents||file.startsWith(`${CURRENT_PROJECT_LAYOUT.agents}/`),hasLegacyMarker||=file===LEGACY_PROJECT_LAYOUT.config||file===LEGACY_AGENT_POLICY_PATH}return hasCurrentProject?"current":hasLegacyProject?"legacy":hasCurrentMarker?"current":hasLegacyMarker?"legacy":null}function getProjectLayoutPaths(layout){return layout==="current"?CURRENT_PROJECT_LAYOUT:LEGACY_PROJECT_LAYOUT}function selectProjectConfigPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)&&!files.has(LEGACY_PROJECT_LAYOUT.config)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}function selectProjectPolicyPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}var CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT,LEGACY_AGENT_POLICY_PATH,init_project_layout=__esm({"src/runtime/project-layout.ts"(){CURRENT_PROJECT_LAYOUT={project:".fimo/project.json",config:".fimo/config.json",agents:".fimo/agents"},LEGACY_PROJECT_LAYOUT={project:".fimo.settings.json",config:"fimo-config.json",agents:"agents"},LEGACY_AGENT_POLICY_PATH="fimo.config.json";__name(detectProjectLayout,"detectProjectLayout");__name(getProjectLayoutPaths,"getProjectLayoutPaths");__name(selectProjectConfigPath,"selectProjectConfigPath");__name(selectProjectPolicyPath,"selectProjectPolicyPath")}});import fs7 from"node:fs";import path7 from"node:path";function existingLayoutPaths(cwd){return[CURRENT_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,CURRENT_PROJECT_LAYOUT.agents,LEGACY_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(file=>fs7.existsSync(path7.join(cwd,file)))}function detectProjectLayoutAtRoot(cwd){return detectProjectLayout(existingLayoutPaths(cwd))}function resolveProjectLayoutPaths(cwd,fallback="current"){return getProjectLayoutPaths(detectProjectLayoutAtRoot(cwd)??fallback)}function resolveProjectSettingsPath(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).project)}function resolveProjectConfigPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectConfigPath(files,detectProjectLayout(files)))}function resolveProjectPolicyPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectPolicyPath(files,detectProjectLayout(files)))}function resolveProjectAgentsDir(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).agents)}function loadProjectSettings(cwd){let settingsPath=resolveProjectSettingsPath(cwd);if(!fs7.existsSync(settingsPath))throw new Error("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project.");return JSON.parse(fs7.readFileSync(settingsPath,"utf-8"))}function findProjectRoot(start){let dir=path7.resolve(start);for(;;){if(fs7.existsSync(path7.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs7.existsSync(path7.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path7.dirname(dir);if(parent===dir)return null;dir=parent}}function resolveProjectCwd(cwdOption){let start=path7.resolve(cwdOption??process.cwd());return findProjectRoot(start)??start}var init_project=__esm({"src/cli/utils/project.ts"(){init_project_layout();__name(existingLayoutPaths,"existingLayoutPaths");__name(detectProjectLayoutAtRoot,"detectProjectLayoutAtRoot");__name(resolveProjectLayoutPaths,"resolveProjectLayoutPaths");__name(resolveProjectSettingsPath,"resolveProjectSettingsPath");__name(resolveProjectConfigPath,"resolveProjectConfigPath");__name(resolveProjectPolicyPath,"resolveProjectPolicyPath");__name(resolveProjectAgentsDir,"resolveProjectAgentsDir");__name(loadProjectSettings,"loadProjectSettings");__name(findProjectRoot,"findProjectRoot");__name(resolveProjectCwd,"resolveProjectCwd")}});import{z as z33}from"zod";function filterUnknownProperties(data,schema){if(data==null)return data;if(schema instanceof z33.ZodOptional||schema instanceof z33.ZodNullable||schema instanceof z33.ZodDefault)return filterUnknownProperties(data,schema.unwrap());if(schema instanceof z33.ZodArray){if(!Array.isArray(data))return data;let itemSchema=schema.unwrap();return data.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z33.ZodDiscriminatedUnion){if(typeof data!="object"||data===null)return data;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z33.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data,matchingSchema):data}if(schema instanceof z33.ZodObject){if(typeof data!="object")return data;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data,key)){let fieldSchema=shape[key],fieldValue2=data[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z33.ZodUnknown)for(let[key,value]of Object.entries(data))key in shape||(result[key]=value);return result}return data}function createObjectDTO(schema){return{schema,from(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z33.ZodObject)return createObjectDTO(schema);if(schema instanceof z33.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z34}from"zod";function createCursorPageDataSchema(dataSchema){return z34.object({items:z34.array(dataSchema),nextCursor:z34.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z34.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema2,createPaginatedResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema2=__name(dataSchema=>z34.object({data:dataSchema}),"createResponseSchema"),createPaginatedResponseSchema=__name(dataSchema=>z34.object({data:z34.array(dataSchema),page:z34.number(),total:z34.number(),totalPages:z34.number(),hasMore:z34.boolean()}),"createPaginatedResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z35}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z35.object({page:z35.coerce.number().int().positive().default(1),limit:z35.coerce.number().int().positive().max(100).default(20)})}});import{z as z36}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common2=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z36.coerce.date(),positiveInt:z36.number().int().positive(),nonNegativeInt:z36.number().int().nonnegative()},BaseEntitySchema=z36.object({id:z36.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z36.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z36.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z36.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z36.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z36.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z36.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z36.enum(["owner","admin","member"]),AssetTypeSchema=z36.enum(["file","folder"]),TemplateCodeSchema=z36.enum(["Free","PAYG","Premium","Pro"]),FieldTypeSchema=z36.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});import{z as z37}from"zod";var MB,MAX_UPLOAD_FILE_SIZE_BYTES,MAX_DOCUMENT_SIZE_BYTES,MAX_AUDIO_SIZE_BYTES,MAX_IMAGE_SIZE_BYTES,MAX_VIDEO_SIZE_BYTES,MAX_ARCHIVE_SIZE_BYTES,MAX_MODEL_SIZE_BYTES,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES,MODEL_MEDIA_TYPE,AttachmentModelMediaTypeSchema,MODEL_MIME_TYPES,MODEL_RENDER_VIEW_ANGLES,AttachmentModelRenderRequestSchema,AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema,AttachmentModelRenderResponseSchema,AttachmentModelRenderMeterSchema,ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";MB=1024*1024,MAX_UPLOAD_FILE_SIZE_BYTES=50*MB,MAX_DOCUMENT_SIZE_BYTES=5*MB,MAX_AUDIO_SIZE_BYTES=10*MB,MAX_IMAGE_SIZE_BYTES=20*MB,MAX_VIDEO_SIZE_BYTES=20*MB,MAX_ARCHIVE_SIZE_BYTES=20*MB,MAX_MODEL_SIZE_BYTES=20*MB,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES=20*MB,MODEL_MEDIA_TYPE={GLB:"model/gltf-binary",GLTF:"model/gltf+json",FBX:"model/fbx",OBJ:"model/obj",STL:"model/stl",PLY:"model/ply"},AttachmentModelMediaTypeSchema=z37.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z37.object({renderId:z37.uuid(),filename:z37.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z37.url()}),AttachmentModelRenderSuccessSchema=z37.object({status:z37.literal("succeeded"),views:z37.tuple([z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z37.url()}),z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z37.url()}),z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z37.url()}),z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z37.url()})]),elapsedMs:z37.number().nonnegative(),browserElapsedMs:z37.number().nonnegative(),diagnostics:z37.unknown().optional()}),AttachmentModelRenderFailureSchema=z37.object({status:z37.literal("failed"),error:z37.literal("render_failed"),message:z37.string(),elapsedMs:z37.number().nonnegative(),browserElapsedMs:z37.number().nonnegative()}),AttachmentModelRenderResponseSchema=z37.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z37.object({browserElapsedMs:z37.number().nonnegative()}),ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:MAX_ARCHIVE_SIZE_BYTES},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLB,extensions:[".glb"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLTF,extensions:[".gltf"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.FBX,extensions:[".fbx"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.OBJ,extensions:[".obj"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.STL,extensions:[".stl"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.PLY,extensions:[".ply"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z38}from"zod";var AssetReadRequestSchema2,AssetDerivedFileSchema,AssetReadBaseSchema,AssetReadPageSchema,AssetReadQuerySchema,AssetReadResultSchema2,init_asset_reading=__esm({"../../packages/api-contracts/dist/esm/types/asset-reading.js"(){"use strict";AssetReadRequestSchema2=z38.object({cursor:z38.string().optional(),query:z38.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),AssetDerivedFileSchema=z38.object({url:z38.url(),mediaType:z38.string(),filename:z38.string()}),AssetReadBaseSchema=z38.object({assetId:z38.uuid(),filename:z38.string(),mediaType:z38.string(),representation:z38.enum(["text","table","document","archive","image","transcript","video","model"]),content:z38.string(),derivedFiles:z38.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z38.literal("page"),start:z38.number().int().nonnegative(),end:z38.number().int().nonnegative(),total:z38.number().int().nonnegative(),nextCursor:z38.string().nullable(),complete:z38.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z38.literal("query"),query:z38.string(),source:z38.enum(["original-file","canonical-text","derived-files"]),truncated:z38.boolean()}),AssetReadResultSchema2=z38.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z39}from"zod";function isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment2(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function branchResourceKey(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${branchResourceKey(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_ANALYTICS_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_ANALYTICS_ENV_KEYS=["VITE_ENABLE_ANALYTICS","NEXT_PUBLIC_FIMO_ENABLE_ANALYTICS","NUXT_PUBLIC_FIMO_ENABLE_ANALYTICS","PUBLIC_FIMO_ENABLE_ANALYTICS"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,...FIMO_ANALYTICS_ENV_KEYS,"VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");BranchSchema=z39.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});import{z as z40}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z40.union([z40.literal(PRODUCTION_ENVIRONMENT_KEY),z40.literal(PREVIEW_ENVIRONMENT_KEY),z40.uuid()]),CustomEnvironmentSchema=z40.object({id:z40.uuid(),projectId:z40.uuid(),name:z40.string().trim().min(1).max(64),branchPatterns:z40.array(z40.string().min(1).max(255)).min(1),description:z40.string().max(255).nullable()}),ResolvedEnvironmentSchema=z40.object({branch:BranchSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});var init_realtime_room=__esm({"../../packages/api-contracts/dist/esm/types/realtime-room.js"(){"use strict";init_env()}});import{z as z41}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z41.preprocess(referenceValuePreprocess,z41.object({documentId:z41.uuid()})),ReferenceInputValueSchema=z41.preprocess(referenceValuePreprocess,z41.union([z41.object({documentId:z41.uuid()}),z41.object({slug:z41.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z41.preprocess(polymorphicReferenceValuePreprocess,z41.object({contentType:z41.string().min(1),documentId:z41.uuid()})),PolymorphicReferenceInputValueSchema=z41.preprocess(polymorphicReferenceValuePreprocess,z41.union([z41.object({contentType:z41.string().min(1),documentId:z41.uuid()}),z41.object({contentType:z41.string().min(1),slug:z41.string().min(1)})]))}});import{z as z42}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path53){let conditionPath=[...path53,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path53)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path53));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path53,fieldName,variant.uid]);else walk(field.schema.fields,[...path53,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path53,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path53,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common2();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z42.union([z42.object({field:z42.string().min(1),equals:z42.union([z42.string(),z42.number(),z42.boolean()])}).strict(),z42.object({field:z42.string().min(1),in:z42.array(z42.union([z42.string(),z42.number(),z42.boolean()])).min(1)}).strict()]),commonFieldShape={label:z42.string().min(1).optional(),description:z42.string().optional(),group:z42.union([z42.string().min(1),z42.array(z42.string().min(1)).min(1)]).optional(),editable:z42.boolean().optional(),required:z42.boolean().optional(),default:z42.unknown().optional(),showIf:z42.union([showIfClauseSchema,z42.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z42.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z42.object({...commonFieldShape,type:z42.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z42.number().optional(),max:z42.number().optional(),minLength:z42.number().int().nonnegative().optional(),maxLength:z42.number().int().nonnegative().optional(),regex:z42.string().optional(),multiple:z42.boolean().optional(),allowedMimeTypes:z42.array(z42.string()).optional(),options:z42.array(z42.string().min(1)).min(1).optional(),unique:z42.boolean().optional(),i18n:z42.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z42.object({...commonFieldShape,type:z42.literal("reference"),target:z42.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z42.array(z42.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z42.boolean().optional(),i18n:z42.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z42.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z42.record(z42.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z42.object({uid:z42.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z42.string().min(1),description:z42.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z42.object({fields:blockFieldsSchema}).strict(),blocksSchema=z42.object({oneOf:z42.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z42.object({...commonFieldShape,type:z42.literal("blocks"),min:z42.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z42.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z42.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z42.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z43}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","project_transfer","project_takedown","project_takedown_lift","organization_takedown","organization_takedown_lift","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_posthog_milestones_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_data_usage_read","ops_agent_provider_errors_read","ops_chat_history_health_read","ops_chat_history_calls_read","ops_chat_history_content_read","ops_chat_history_judge_calibration","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_intake_read","ops_pylon_queue_read","ops_support_report_change","ops_billing_read","ops_billing_agent_runtime_activate","ops_billing_entitlements_sync","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","ops_agent_branch_discard","admin_resource_read","merge_force"],AuditActionSchema=z43.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z43.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z43.enum(AUDIT_ACTOR_KINDS)}});import{z as z44}from"zod";function refineChatHistoryWindow(schema){return schema.refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"chat history windows cannot exceed 7 days"})}var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,LegacyAdoptionMutationInputSchema,LegacyAdoptionAbandonInputSchema,LegacyAdoptionActivationInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,OPS_POSTHOG_EVENTS,OPS_POSTHOG_QUESTION,OpsPosthogTimestampSchema,OpsPosthogMilestonesInputSchema,OpsPosthogFailureCodeSchema,OpsPosthogCoverageSchema,OpsPosthogCountsSchema,OpsPosthogMilestonesResponseSchema,OpsSessionHealthInputSchema,OpsProjectAnalyticsHealthInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";init_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z44.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:platform:legacy-adoption","ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:project:branch:discard","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:posthog:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z44.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:OPS_PERMISSIONS.filter(permission=>permission!=="ops:platform:legacy-adoption")},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z44.object({permissions:z44.array(OpsPermissionSchema).min(1),backendProfiles:z44.array(OpsBackendProfileSchema).min(1),enabled:z44.boolean().default(!0)}),LegacyAdoptionMutationInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3),confirmProduction:z44.boolean().default(!1)}),LegacyAdoptionAbandonInputSchema=LegacyAdoptionMutationInputSchema.extend({recordId:z44.uuid()}),LegacyAdoptionActivationInputSchema=LegacyAdoptionMutationInputSchema.extend({oldDeployment:z44.string().trim().min(1).max(200),legacyWritersStopped:z44.literal(!0)}),OpsServiceTokenInputSchema=z44.object({name:z44.string().trim().min(1).max(120),permissions:z44.array(OpsPermissionSchema).min(1),backendProfiles:z44.array(OpsBackendProfileSchema).min(1),expiresAt:z44.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z44.object({importanceReason:z44.string().trim().min(1).max(1e3),ownerUserId:z44.string().trim().min(1).nullable().optional(),framework:z44.string().trim().max(120).nullable().optional(),packageManager:z44.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z44.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z44.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z44.object({projectId:z44.uuid(),title:z44.string().trim().min(1).max(240),userReport:z44.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z44.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z44.string().trim().max(1e4).nullable().optional(),outcome:z44.string().trim().max(1e4).nullable().optional(),evidence:z44.array(z44.record(z44.string(),z44.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z44.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z44.object({fingerprint:z44.string().trim().min(1).max(240),title:z44.string().trim().min(1).max(240),description:z44.string().trim().min(1).max(1e4),affectedVersions:z44.array(z44.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z44.array(z44.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z44.string().trim().min(1).max(64).nullable().optional(),workaround:z44.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z44.array(z44.string().trim().min(1).max(120)).max(100),detectionQueries:z44.array(z44.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z44.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z44.object({changeReference:z44.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z44.string().trim().min(1).max(1e4),evidence:z44.array(z44.record(z44.string(),z44.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z44.object({recipientEmail:z44.email().optional(),subject:z44.string().trim().min(1).max(200).default("An update from Fimo"),message:z44.string().trim().min(1).max(5e3),locale:z44.string().trim().min(2).max(20),reason:z44.string().trim().min(1).max(1e3),acknowledgePolicy:z44.literal(!0)}),OpsPylonIssueIdSchema=z44.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z44.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z44.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z44.string().trim().min(1).max(255),OpsPylonEmailListSchema=z44.array(z44.email()).max(50).default([]),OpsPylonResolveInputSchema=z44.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z44.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z44.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z44.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z44.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z44.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z44.object({projectId:z44.uuid(),from:z44.coerce.date(),to:z44.coerce.date(),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z44.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z44.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z44.object({projectId:z44.uuid().optional(),organizationId:z44.string().trim().min(1).max(255).optional(),agentKey:z44.string().trim().min(1).max(120).optional(),threadId:z44.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z44.coerce.date().optional(),minCostUsd:z44.coerce.number().min(0).optional(),tracedOnly:z44.coerce.boolean().default(!1),limit:z44.coerce.number().int().min(1).max(100).default(25),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z44.object({limit:z44.coerce.number().int().min(1).max(500).default(200),reason:z44.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z44.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z44.object({maxChars:z44.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z44.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z44.object({messageIndex:z44.coerce.number().int().min(0).optional(),maxChars:z44.coerce.number().int().min(500).max(2e5).default(2e4),reason:z44.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z44.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z44.strictObject({projectId:z44.uuid().optional(),organizationId:z44.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z44.string().trim().min(1).max(120).optional(),since:z44.coerce.date(),until:z44.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z44.coerce.boolean().default(!1),limit:z44.coerce.number().int().min(1).max(200).default(50),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OPS_DATA_USAGE_MAX_WINDOW_MS=10080*60*1e3,OpsDataUsageGroupBySchema=z44.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z44.strictObject({organizationId:z44.string().trim().min(1).max(255).optional(),since:z44.coerce.date(),until:z44.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z44.coerce.number().int().min(1).max(200).default(50),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_DATA_USAGE_MAX_WINDOW_MS,{path:["since"],message:"data usage window cannot exceed 7 days"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z44.object({projectId:z44.uuid().optional(),since:z44.coerce.date(),until:z44.coerce.date().optional(),limit:z44.coerce.number().int().min(1).max(1e3).default(500),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z44.uuid().optional(),since:z44.coerce.date(),until:z44.coerce.date().default(()=>new Date),reason:z44.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z44.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z44.strictObject({...opsChatHistoryWindow,limit:z44.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z44.strictObject({...opsChatHistoryWindow,sample:z44.coerce.number().int().min(1).max(25).default(10)})),OpsChatHistoryJudgeCalibrationInputSchema=z44.strictObject({reason:z44.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z44.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z44.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z44.object({since:z44.coerce.date(),until:z44.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z44.coerce.number().min(0).optional(),limit:z44.coerce.number().int().min(1).max(200).default(50),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z44.object({since:z44.coerce.date(),until:z44.coerce.date().default(()=>new Date),model:z44.string().trim().min(1).max(120).optional(),provider:z44.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z44.coerce.date().optional(),limit:z44.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z44.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z44.boolean().default(!1),correlationLimit:z44.coerce.number().int().min(1).max(100).default(25),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=10080*60*1e3,{path:["since"],message:"provider error windows cannot exceed 7 days"}).refine(input=>!input.before||input.before>=input.since&&input.before<=input.until,{path:["before"],message:"before must be within the requested window"}),OpsBillingCacheInvalidateInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z44.object({reason:z44.string().trim().min(1).max(500),apply:z44.boolean().default(!1),confirmProduction:z44.boolean().default(!1),cursor:z44.string().min(1).optional(),batchSize:z44.number().int().min(1).max(100).default(50),concurrency:z44.number().int().min(1).max(10).default(2)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish","agent-branch.discard"],OpsProjectOperationKindSchema=z44.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z44.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z44.discriminatedUnion("kind",[z44.object({kind:z44.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z44.object({kind:z44.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z44.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z44.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z44.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z44.object({migrationId:OpsMigrationIdSchema,projectEnv:z44.string().trim().min(1).max(255).default("main"),reason:z44.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z44.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z44.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z44.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z44.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z44.object({pattern:z44.string().min(1).max(300).optional(),limit:z44.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z44.object({pattern:z44.string().min(1).max(200),include:z44.string().min(1).max(300).optional(),caseInsensitive:z44.boolean().default(!1),maxMatches:z44.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z44.object({path:OpsProjectFilePathSchema,content:z44.string().max(256*1024),overwrite:z44.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z44.string().trim().length(64),consentReference:z44.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z44.intersection(OpsProjectOperationPlanInputSchema,z44.object({planHash:z44.string().trim().length(64),reason:z44.string().trim().min(1).max(1e3),consentReference:z44.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z44.object({planHash:z44.string().trim().length(64),reason:z44.string().trim().min(1).max(1e3),consentReference:z44.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z44.iso.datetime({offset:!0}).refine(value=>Number.isFinite(Date.parse(value))&&!/\.\d{3}\d*[1-9]\d*(?:Z|[+-]\d{2}:\d{2})$/.test(value),"A finite timestamp with at most millisecond precision is required").transform(value=>new Date(value).toISOString()),OpsPosthogMilestonesInputSchema=z44.strictObject({projectId:z44.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z44.string().trim().min(1).max(1e3)}).refine(value=>{let duration=Date.parse(value.to)-Date.parse(value.from);return duration>0&&duration<=1440*60*1e3},{message:"Window must satisfy from < to and be at most 24 hours",path:["to"]}),OpsPosthogFailureCodeSchema=z44.enum(["not_configured","unauthenticated","forbidden","backend_mismatch","invalid_request","provider_auth_failed","provider_project_unavailable","rate_limited","timeout","provider_error","capability_unavailable","invalid_response","incomplete","pending","audit_unavailable"]),OpsPosthogCoverageSchema=z44.strictObject({completeAggregate:z44.boolean(),truncated:z44.boolean().nullable(),sampled:z44.boolean().nullable(),pagination:z44.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z44.literal(!1),providerAsOf:z44.null(),projectFilter:z44.literal("exact properties.projectId equality"),environmentFilterSupported:z44.literal(!1),excludesMissingProjectId:z44.literal(!0),transport:z44.literal("server"),consentCoverage:z44.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z44.literal(!1)}),OpsPosthogCountsSchema=z44.array(z44.strictObject({event:z44.enum(OPS_POSTHOG_EVENTS),captureCount:z44.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z44.strictObject({schemaVersion:z44.literal(1),questionId:z44.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z44.uuid().nullable(),projectEnvironment:z44.literal("mixed_or_unrecorded"),window:z44.strictObject({from:z44.iso.datetime(),to:z44.iso.datetime(),bounds:z44.literal("[from,to)")}).nullable(),source:z44.literal("posthog"),sourceStatus:z44.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z44.iso.datetime(),auditId:z44.uuid().nullable(),counts:OpsPosthogCountsSchema.nullable(),coverage:OpsPosthogCoverageSchema}).superRefine((value,ctx)=>{(value.sourceStatus==="available"?value.counts===null||value.failureCode!==null||value.auditId===null||value.projectId===null||value.window===null||!value.coverage.completeAggregate||value.coverage.sampled!==!1||value.coverage.truncated!==!1||value.coverage.pagination!=="not_applicable":value.counts!==null||value.failureCode===null||value.coverage.completeAggregate)&&ctx.addIssue({code:"custom",message:"Invalid aggregate availability"})}),OpsSessionHealthInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3),limit:z44.number().int().min(1).max(100).default(25),checkProvider:z44.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z44.object({branch:z44.string().trim().min(1).max(255),canaryPath:z44.string().max(300).regex(/^\/[a-zA-Z0-9/_-]*\?fimo_monitor=[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/).optional(),since:z44.iso.datetime({offset:!0}),until:z44.iso.datetime({offset:!0}),reason:z44.string().trim().min(1).max(1e3)}).strict().refine(input=>Date.parse(input.since)<=Date.parse(input.until),{path:["since"],message:"since must be before or equal to until"}).refine(input=>Date.parse(input.until)-Date.parse(input.since)<=10080*60*1e3,{path:["since"],message:"analytics health window cannot exceed 7 days"}).refine(input=>Date.parse(input.until)<=Date.now(),{path:["until"],message:"until cannot be in the future"}).transform(({since,until,...input})=>({...input,since:new Date(since),until:new Date(until)}))}});import{z as z45}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z45.object({kind:z45.literal("say"),label:z45.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z45.string().min(1).max(240).optional(),message:z45.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z45.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z45.discriminatedUnion("command",[z45.object({kind:z45.literal("app"),command:z45.literal("publish")}).strict(),z45.object({kind:z45.literal("app"),command:z45.literal("connect"),integrationKey:z45.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z45.object({fallback:z45.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z45.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z45.literal("choices"),text:z45.string().max(500).optional(),actions:z45.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z45.discriminatedUnion("kind",[z45.object({kind:z45.literal("entry"),collection:z45.string().min(1).max(80),entryId:z45.string().min(1).max(120)}),z45.object({kind:z45.literal("asset"),assetId:z45.string().min(1).max(120)}),z45.object({kind:z45.literal("url"),url:z45.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z45.literal("table"),columns:z45.array(z45.object({label:z45.string().min(1).max(24)})).min(2).max(4),rows:z45.array(z45.object({cells:z45.array(z45.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z45.literal("cards"),layout:z45.enum(["rail","stack"]).optional(),items:z45.array(z45.object({title:z45.string().min(1).max(60),subtitle:z45.string().min(1).max(120).optional(),imageUrl:z45.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z45.literal("entry"),label:z45.string().min(1).max(80),collection:z45.string().min(1).max(80),entryId:z45.string().min(1).max(120),path:z45.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z45.literal("assets"),items:z45.array(z45.object({url:z45.url({protocol:/^https$/}).max(2e3),alt:z45.string().min(1).max(120),label:z45.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z45.literal("callout"),title:z45.string().min(1).max(80),text:z45.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z45.literal("stat"),items:z45.array(z45.object({label:z45.string().min(1).max(24),value:z45.string().min(1).max(16),delta:z45.string().min(1).max(12).optional(),tone:z45.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z45.literal("chart"),unit:z45.string().min(1).max(12).optional(),points:z45.array(z45.object({label:z45.string().min(1).max(12),value:z45.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z45.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z45.literal("text"),placeholder:z45.string().min(1).max(120).optional(),multiline:z45.boolean().optional()}).strict(),ChatFormStepIdSchema=z45.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z45.object({id:ChatFormStepIdSchema,token:z45.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z45.string().trim().min(1).max(60),reason:z45.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z45.literal("capabilities"),items:z45.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z45.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z45.object({id:ChatFormStepIdSchema.optional(),question:z45.string().min(1).max(500),header:z45.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z45.boolean().optional(),recommended:z45.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."}),step.body.type==="capabilities"&&step.multiSelect===!1&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}).transform(step=>({...step,multiSelect:step.multiSelect??step.body.type==="capabilities"})),FormBlockSchema=BlockBaseSchema.extend({type:z45.literal("form"),steps:z45.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z45.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z45.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z45.object({stepId:ChatFormStepIdSchema.optional(),header:z45.string().min(1).max(25),question:z45.string().min(1).max(500),answer:z45.string().min(1),selectedLabels:z45.array(z45.string().min(1).max(120)).max(8),freeText:z45.string(),skipped:z45.boolean()}),ChatFormAnswerMetadataSchema=z45.object({toolCallId:z45.string().max(255).optional(),shortTitle:z45.string().max(80).optional(),questions:z45.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z45.object({version:z45.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z45.object({version:z45.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z45.string().min(1).max(255),partial:z45.boolean().optional()})}});import{z as z46}from"zod";var CHAT_PORTRAIT_SHAPES,CHAT_PORTRAIT_FACES,CHAT_PORTRAIT_COLORS,ChatPortraitSchema,init_chat_portrait=__esm({"../../packages/api-contracts/dist/esm/types/chat-portrait.js"(){"use strict";CHAT_PORTRAIT_SHAPES=["pebble","bean","cloud","drop","potato","mochi","bun","pillow"],CHAT_PORTRAIT_FACES=["happy","joy","bright","smile","calm","surprised","squint","cat"],CHAT_PORTRAIT_COLORS=["red","orange","amber","lime","emerald","teal","sky","blue","indigo","violet","fuchsia","pink"],ChatPortraitSchema=z46.object({shape:z46.enum(CHAT_PORTRAIT_SHAPES),face:z46.enum(CHAT_PORTRAIT_FACES),color:z46.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z47}from"zod";function normalizeStoredBlock(block){if(typeof block!="object"||block===null||Array.isArray(block))return block;let{type,...rest}=block;if(typeof type!="string")return block;let target=LEGACY_BLOCK_TYPES[type];return target?target==="viz"?{...rest,type:target,kind:"bar"}:{...rest,type:target}:block}function normalizeStoredBlocks(blocks){return Array.isArray(blocks)?blocks.map(normalizeStoredBlock):blocks}function normalizeStoredDocument(document){if(typeof document!="object"||document===null||Array.isArray(document))return document;let source=document;return{...source,brief:normalizeStoredBlocks(source.brief),details:normalizeStoredBlocks(source.details)}}function normalizeReportDocument(document){return document==null?null:StoredReportDocumentSchema.parse(document)}function derivedBlockBody(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"viz":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"list":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"media":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
180
+ `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start=getFirstKeyStartProps(prev);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev=getPrevProps(parent),start=getFirstKeyStartProps(prev);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser}});var require_public_api=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer(),Document=require_Document(),errors=require_errors(),log=require_log(),identity2=require_identity(),lineCounter=require_line_counter(),parser=require_parser();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2))),doc}__name(parseDocument,"parseDocument");function parse12(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse12,"parse");function stringify4(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document.Document(value,_replacer,options).toString(options)}__name(stringify4,"stringify");exports2.parse=parse12;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument;exports2.stringify=stringify4}});var require_dist=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer(),Document=require_Document(),Schema=require_Schema(),errors=require_errors(),Alias=require_Alias(),identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),cst=require_cst(),lexer=require_lexer(),lineCounter=require_line_counter(),parser=require_parser(),publicApi=require_public_api(),visit2=require_visit();exports2.Composer=composer.Composer;exports2.Document=Document.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors.YAMLError;exports2.YAMLParseError=errors.YAMLParseError;exports2.YAMLWarning=errors.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import{createHash as createHash2}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash2("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs2 from"node:fs";import{homedir}from"node:os";import path3,{join}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function readReleaseManifest(){try{let raw=fs2.readFileSync(RELEASE_FILE2,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE2,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath2(import.meta.url),CLI_ROOT=path3.resolve(path3.dirname(THIS_FILE),"..",".."),RELEASE_FILE2=path3.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs4 from"node:fs";function ensureCredentialsDir(cfg){fs4.existsSync(cfg.credentialsDir)||fs4.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs4.existsSync(cfg.credentialsFile))return null;let raw=fs4.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs4.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs4.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs4.existsSync(cfg.credentialsFile)&&fs4.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{z as z5}from"zod";function createResponseSchema(dataSchema){return z5.object({data:dataSchema})}function encodeBranchPathSegment(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId,suffix){return`/management/projects/${encodeURIComponent(projectId)}${suffix}`}function managementBranchPath(projectId,branch,suffix){return managementProjectPath(projectId,`/branches/${encodeBranchPathSegment(branch)}${suffix}`)}function tenantPath(projectId,branch,suffix){return`/tenant/${encodeURIComponent(projectId)}/branches/${encodeBranchPathSegment(branch)}${suffix}`}function addQuery(path53,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&&params.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path53}?${queryString}`:path53}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z5.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor))throw new Error("Invalid pagination cursor.");let base64=cursor.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z5.object({items:z5.array(itemSchema),nextCursor:z5.string().nullable(),total:z5.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema,"createResponseSchema");uuidSchema=z5.uuid(),sessionStatusSchema=z5.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z5.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z5.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z5.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z5.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z5.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z5.string().nullable().optional(),goal:z5.string().nullable().optional(),provenance:z5.object({source:z5.enum(["studio","slack","autonomous","mcp"]),creator:z5.object({kind:z5.enum(["user","slack","agent","oauth","conversation"]),id:z5.string()}),conversationId:z5.string().nullable(),runId:z5.string().nullable()}).nullable().optional(),createdBy:z5.string().optional(),createdAt:z5.iso.datetime().optional(),savedRevision:z5.string().nullable().optional(),targetBranch:z5.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z5.string().min(1)}),workingBranch:z5.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z5.url().nullable(),lastActivityAt:z5.iso.datetime(),expiresAt:z5.iso.datetime().nullable(),retention:z5.enum(["temporary","durable"]).optional(),visibility:z5.enum(["internal","user-visible"]).optional(),onExpire:z5.enum(["discard","keep"]),nextOperations:z5.array(z5.string())}),paginationShape={limit:z5.number().int().min(1).max(100).optional(),cursor:z5.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z5.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z5.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor=>cursor==null||/^[1-9]\d*$/.test(cursor)&&Number.isSafeInteger(Number(cursor)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z5.object({data:z5.array(z5.unknown()),meta:z5.object({limit:z5.number().int().positive(),offset:z5.number().int().nonnegative(),total:z5.number().int().nonnegative(),hasMore:z5.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z6}from"zod";function projectAgentSessionsPage(body){let page=body;if(!Array.isArray(page.data))throw new Error("Expected an agent sessions page.");let result=cliAgentSessionsPageSchema.parse({...page,data:page.data.map(value=>{let{env,...session}=value;return{...session,branch:session.branch??env}})});return{...result,items:result.data,nextCursor:result.hasMore?String(result.page+1):null}}function projectAgentStatus(body){let data=recordValue(responseData(body),"Expected an agent session response."),session=recordValue(data.session,"Expected an agent session.");if(!Array.isArray(data.checkpoints))throw new Error("Expected agent session checkpoints.");return agentStatusOutputSchema.parse({data:{session:{...session,branch:session.branch??session.env},checkpoints:data.checkpoints}})}var agentTriggerKindSchema,agentCapabilitySchema,agentListItemSchema,agentListResponseSchema,manualAgentRunResponseSchema,publicAgentSessionSchema,publicAgentCheckpointSchema,agentStatusOutputSchema,cliAgentSessionSchema,cliAgentSessionsPageSchema,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common();agentTriggerKindSchema=z6.enum(["manual","schedule","webhook"]),agentCapabilitySchema=z6.object({token:z6.string().min(1),risk:z6.enum(["low","medium","high","critical"]),description:z6.string()}),agentListItemSchema=z6.object({name:z6.string().min(1),description:z6.string().nullable(),goalFirstLine:z6.string().nullable(),declaredCapabilities:z6.array(agentCapabilitySchema),triggers:z6.array(z6.object({kind:agentTriggerKindSchema,summary:z6.string()})),triggerStates:z6.array(z6.object({triggerIndex:z6.number().int().nonnegative(),triggerKind:agentTriggerKindSchema,enabled:z6.boolean(),wired:z6.boolean(),syncError:z6.string().nullable()})),availability:z6.enum(["available","pending_merge"]),paused:z6.boolean(),nextRunAt:z6.iso.datetime().nullable()}),agentListResponseSchema=createResponseSchema(z6.array(agentListItemSchema)),manualAgentRunResponseSchema=createResponseSchema(z6.union([z6.object({sessionId:z6.string().min(1)}),z6.object({skipped:z6.enum(["no-manual-trigger","agent-not-deployed","agent-config-invalid","manual-trigger-not-synced","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])})])),publicAgentSessionSchema=z6.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,agentName:z6.string().min(1),triggerKind:agentTriggerKindSchema,status:z6.enum(["planned","running","finished","cancelled","errored"]),startedAt:z6.iso.datetime().nullable(),finishedAt:z6.iso.datetime().nullable(),cancelledAt:z6.iso.datetime().nullable(),terminalReason:z6.string().nullable(),errorMessage:z6.string().nullable(),reportDocument:z6.unknown().nullable(),reviewSummary:z6.unknown().nullable(),reviewCaptureError:z6.string().nullable(),createdAt:z6.iso.datetime(),updatedAt:z6.iso.datetime()}),publicAgentCheckpointSchema=z6.object({id:uuidSchema,sessionId:uuidSchema,checkpointIdx:z6.number().int().nonnegative(),payloadSizeBytes:z6.number().int().nonnegative(),checksum:z6.string().length(64),createdAt:z6.iso.datetime()}),agentStatusOutputSchema=createResponseSchema(z6.object({session:publicAgentSessionSchema,checkpoints:z6.array(publicAgentCheckpointSchema)})),cliAgentSessionSchema=z6.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,agentName:z6.string().min(1),triggerKind:agentTriggerKindSchema,status:z6.enum(["planned","running","finished","cancelled","errored"]),startedAt:z6.iso.datetime().nullable(),finishedAt:z6.iso.datetime().nullable(),cancelledAt:z6.iso.datetime().nullable(),costUsd:z6.number().nonnegative().optional(),costCeilingUsd:z6.number().nonnegative(),creditsUsed:z6.number().int().nonnegative().nullable().optional(),terminalReason:z6.string().nullable(),errorMessage:z6.string().nullable(),reportDocument:z6.unknown().nullable(),reviewSummary:z6.unknown().nullable(),reviewCaptureError:z6.string().nullable(),createdAt:z6.iso.datetime(),updatedAt:z6.iso.datetime()}).passthrough(),cliAgentSessionsPageSchema=z6.object({data:z6.array(cliAgentSessionSchema),page:z6.number().int().positive(),limit:z6.number().int().positive().optional(),total:z6.number().int().nonnegative(),totalPages:z6.number().int().nonnegative(),hasMore:z6.boolean()});__name(projectAgentSessionsPage,"projectAgentSessionsPage");__name(projectAgentStatus,"projectAgentStatus");agentsOperations={"agents.list":{domain:"agents",summary:"List site agent bundles, triggers, and activation state from main.",accessScope:"read",effect:"read",inputSchema:z6.object({projectId:uuidSchema}).strict(),outputSchema:agentListResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementBranchPath(projectId,"main","/agents")}),"buildRequest")},"agents.run":{domain:"agents",summary:"Trigger one manual site agent run from main.",accessScope:"agents",effect:"mutation",inputSchema:z6.object({projectId:uuidSchema,agentName:z6.string().min(1).max(120),args:z6.record(z6.string(),z6.unknown()).optional()}).strict(),outputSchema:manualAgentRunResponseSchema,buildRequest:__name(({projectId,agentName,args})=>({method:"POST",path:managementBranchPath(projectId,"main",`/agents/${encodeURIComponent(agentName)}/run`),body:args===void 0?{}:{args}}),"buildRequest")},"agents.status":{domain:"agents",summary:"Read one agent run status, report, and safe checkpoint metadata.",accessScope:"read",effect:"read",inputSchema:z6.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:agentStatusOutputSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/agents/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest"),projectOutput:projectAgentStatus},"agents.runs":{domain:"agents",summary:"List site agent runs with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z6.object({projectId:uuidSchema,agentName:z6.string().min(1).optional(),branch:branchNameSchema.optional(),status:z6.enum(["planned","running","finished","cancelled","errored"]).optional(),...numberedPaginationShape,limit:z6.number().int().min(1).max(200).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:cliAgentSessionsPageSchema.extend({items:z6.array(cliAgentSessionSchema),nextCursor:z6.string().nullable()}),buildRequest:__name(({projectId,agentName,branch,status,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/agents/sessions"),{agent_name:agentName,env:branch,status,page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:projectAgentSessionsPage}}}});import{z as z7}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z7.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z7.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z7.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z7.union([z7.literal(7),z7.literal(30),z7.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z7.object({date:z7.string(),content:z7.string(),updatedAt:z7.string(),updatedByUserId:z7.string()}),analyticsBreakdownSchema=z7.object({key:z7.string(),visitors:z7.number().int().nonnegative(),pageviews:z7.number().int().nonnegative()}),analyticsPageBreakdownSchema=z7.object({path:z7.string(),pageName:z7.string().nullable().optional(),visitors:z7.number().int().nonnegative(),pageviews:z7.number().int().nonnegative()}),analyticsPageviewsSchema=z7.object({range:z7.object({preset:analyticsPresetSchema,requestedFrom:z7.string(),requestedTo:z7.string(),effectiveFrom:z7.string(),effectiveTo:z7.string(),isRetentionLimited:z7.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z7.number().int().nonnegative(),pageviews:z7.number().int().nonnegative(),botPageviews:z7.number().int().nonnegative().default(0),botVisitors:z7.number().int().nonnegative().default(0),bounceRate:z7.number().min(0).max(100),viewsPerVisit:z7.number().nonnegative(),averageVisitDurationSeconds:z7.number().nonnegative(),visitorsSeries:z7.array(z7.object({date:z7.string(),visitors:z7.number().int().nonnegative()})),topPages:z7.array(analyticsPageBreakdownSchema),topBrowsers:z7.array(analyticsBreakdownSchema),topDevices:z7.array(analyticsBreakdownSchema),topBots:z7.array(analyticsBreakdownSchema).default([]),topAiAssistants:z7.array(analyticsBreakdownSchema).default([]),topCountries:z7.array(analyticsBreakdownSchema),topSources:z7.array(analyticsBreakdownSchema),annotations:z7.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z7.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z7.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z7.array(z7.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z7.object({branch:branchNameSchema,annotations:z7.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z7.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z7.object({projectId:uuidSchema,branch:branchNameSchema,date:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z7.string().max(500)}).strict(),outputSchema:z7.union([analyticsAnnotationResponseSchema,z7.null()]),buildRequest:__name(({projectId,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z7.object({projectId:uuidSchema,branch:branchNameSchema,date:z7.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z7.null(),buildRequest:__name(({projectId,branch,date})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z8}from"zod";var assetPathItemSchema,AssetDTOSchema,AssetResponseSchema,AssetReadRequestSchema,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema,GenerateResponseSchema,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common();assetPathItemSchema=z8.object({id:z8.string(),name:z8.string()}),AssetDTOSchema=z8.object({id:z8.string(),name:z8.string(),type:z8.enum(["file","folder"]),originalFileName:z8.string().nullable(),parentId:z8.string().nullable(),mimeType:z8.string().nullable(),fileSize:z8.number().nullable(),url:z8.string().nullable(),storageKey:z8.string().nullable(),slug:z8.string(),tags:z8.array(z8.string()).nullable().optional(),createdAt:z8.string().nullable(),updatedAt:z8.string().nullable(),altText:z8.string().nullable().optional(),caption:z8.string().nullable().optional(),aiCaption:z8.string().nullable().optional(),aiAltText:z8.string().nullable().optional(),aiTags:z8.array(z8.string()).nullable().optional(),aiPrimaryColor:z8.string().nullable().optional(),aiProcessingStatus:z8.string().nullable().optional(),width:z8.number().nullable().optional(),height:z8.number().nullable().optional(),path:z8.array(assetPathItemSchema).optional(),hasChildren:z8.boolean().optional()}),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetReadRequestSchema=z8.object({cursor:z8.string().nullable().optional(),query:z8.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z8.object({url:z8.url(),mediaType:z8.string(),filename:z8.string()}),assetReadBaseSchema=z8.object({assetId:z8.uuid(),filename:z8.string(),mediaType:z8.string(),representation:z8.enum(["text","table","document","archive","image","transcript","video","model"]),content:z8.string(),derivedFiles:z8.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema=z8.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z8.literal("page"),start:z8.number().int().nonnegative(),end:z8.number().int().nonnegative(),total:z8.number().int().nonnegative(),nextCursor:z8.string().nullable(),complete:z8.boolean()}),assetReadBaseSchema.extend({mode:z8.literal("query"),query:z8.string(),source:z8.enum(["original-file","canonical-text","derived-files"]),truncated:z8.boolean()})]),GenerateResponseSchema=createResponseSchema(z8.object({jobId:z8.string(),status:z8.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z8.string().nullable().optional(),credits:z8.number().optional(),costUsd:z8.number().optional(),billingMode:z8.enum(["fimo-credits","provider-account"]).optional(),task:z8.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z8.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema),successMessageResponseSchema=z8.object({data:z8.object({message:z8.literal("success")})}),assetGenerationInputSchema=z8.object({projectId:uuidSchema,branch:branchNameSchema,task:z8.string().min(1).optional(),model:z8.string().min(1).optional(),options:z8.record(z8.string(),z8.unknown()),name:z8.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z8.string().max(2e3).optional(),caption:z8.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z8.object({projectId:uuidSchema,sessionId:uuidSchema,url:z8.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z8.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z8.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z8.string().max(1024).refine(path53=>path53.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path53=>path53.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z8.string().max(2e3).optional(),caption:z8.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z8.string().max(200).optional(),type:z8.enum(["file","folder"]).optional(),mimePrefix:z8.string().max(50).optional(),sortBy:z8.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z8.enum(["asc","desc"]).optional(),includePath:z8.boolean().optional(),excludeHidden:z8.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema(AssetReadResultSchema),buildRequest:__name(({projectId,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema,buildRequest:__name(({projectId,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema}),buildRequest:__name(({projectId,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,name:z8.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema,buildRequest:__name(({projectId,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z8.record(z8.string(),z8.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.record(z8.string(),z8.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z8.record(z8.string(),z8.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.record(z8.string(),z8.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z8.unknown(),buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z8.record(z8.string(),z8.unknown()),buildRequest:__name(({projectId,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z8.object({data:z8.record(z8.string(),z8.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema,buildRequest:__name(({projectId,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z8.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z9}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common();creditBalanceOutputSchema=z9.object({projectId:uuidSchema,organizationId:z9.string(),balance:z9.object({totalAvailable:z9.number(),nearLimit:z9.boolean(),canUseAi:z9.boolean(),buckets:z9.object({dailyFreeAvailable:z9.number(),monthlyAvailable:z9.number(),purchasedAvailable:z9.number(),awardedAvailable:z9.number()})}),allowances:z9.object({dailyCredits:z9.object({periodCap:z9.number(),dailyGrant:z9.number(),usedThisPeriod:z9.number(),remainingThisPeriod:z9.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z9.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z10}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z10.object({ok:z10.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z10.array(z10.object({surface:backendSurfaceSchema,count:z10.number().int().nonnegative()})),conflicts:z10.array(backendConflictSchema).optional(),summary:z10.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z10.object({mergeId:uuidSchema,conflicts:z10.array(backendConflictSchema),draftResolutions:z10.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z10.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z10.object({data:z10.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report=z10.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z10.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z10.array(backendSurfaceDeltaSchema).max(6),crossSurface:z10.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report.branch??report.env,against:report.vs,state:report.syncState==="in-sync"?"clean":"changed",syncState:report.syncState,generatedAt:report.generatedAt,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report=z10.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z10.string().min(1),surfaces:z10.array(backendSurfaceDeltaSchema).max(6),crossSurface:z10.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report.fromBranch??report.fromEnv,against:report.toBranch??report.toEnv,generatedAt:report.generatedAt,fingerprint:report.fingerprint,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common();branchSchema=z10.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z10.enum(["provisioning","active","deleted"]),kind:z10.enum(["user","agent-session"]),createdAt:z10.string().optional(),updatedAt:z10.string().optional(),createdBy:z10.string().nullable().optional(),deletedAt:z10.string().nullable().optional()}).passthrough(),branchResponseSchema=z10.object({data:branchSchema}),branchSurfaceStatusSchema=z10.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z10.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z10.iso.datetime(),backendCrossSurfaceFindingSchema=z10.object({id:z10.string(),kind:z10.string(),description:z10.string(),severity:z10.enum(["warning","error"]),source:z10.object({surface:backendSurfaceSchema,key:z10.string()}),target:z10.object({surface:backendSurfaceSchema,key:z10.string()}),actions:z10.array(z10.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z10.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z10.number().int().nonnegative(),conflictCount:z10.number().int().nonnegative(),items:z10.array(z10.object({verb:branchDeltaVerbSchema,key:z10.string(),detail:z10.string().optional(),origin:z10.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z10.record(z10.string(),z10.unknown()).optional()})).max(1e3).optional(),truncated:z10.boolean().optional(),error:z10.string().optional()}),branchSurfaceSummarySchema=z10.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z10.number().int().nonnegative(),conflictCount:z10.number().int().nonnegative(),error:z10.string().optional(),items:z10.array(z10.object({verb:branchDeltaVerbSchema,key:z10.string(),detail:z10.string().optional(),origin:z10.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z10.record(z10.string(),z10.unknown()).optional()})).optional(),truncated:z10.boolean().optional()}),branchStatusOutputSchema=z10.object({branch:branchNameSchema,against:branchNameSchema,state:z10.enum(["clean","changed"]),syncState:z10.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z10.array(branchSurfaceSummarySchema).max(6),crossSurface:z10.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z10.object({verb:branchDeltaVerbSchema,key:z10.string(),detail:z10.string().optional(),meta:z10.record(z10.string(),z10.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z10.string().min(1),surfaces:z10.array(branchSurfaceSummarySchema.extend({truncated:z10.boolean(),items:z10.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z10.object({path:z10.string(),state:z10.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z10.string(),additions:z10.number().int().nonnegative(),deletions:z10.number().int().nonnegative()}),contentSnapshotSchema=z10.object({id:z10.string(),slug:z10.string(),contentType:z10.string(),data:z10.record(z10.string(),z10.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z10.object({collection:z10.string(),rowId:z10.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z10.object({name:z10.string(),label:z10.string(),isSingleton:z10.boolean(),fields:z10.record(z10.string(),z10.unknown())}),schemaDiffOutputSchema=z10.object({typeName:z10.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z10.object({id:z10.string(),name:z10.string(),type:z10.enum(["file","folder"]),mimeType:z10.string().nullable(),storageKey:z10.string().nullable(),url:z10.string().nullable(),fileSize:z10.number().nullable(),width:z10.number().nullable(),height:z10.number().nullable(),altText:z10.string().nullable(),caption:z10.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z10.object({assetId:z10.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z10.object({locale:z10.string(),key:z10.string(),parent:z10.string().nullable(),child:z10.string().nullable()}),formSnapshotSchema=z10.object({formName:z10.string(),label:z10.string().nullable(),schemaFingerprint:z10.string(),fields:z10.record(z10.string(),z10.unknown())}),formDiffOutputSchema=z10.object({formName:z10.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z10.object({surface:backendSurfaceSchema,key:z10.string(),kind:z10.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z10.string(),parentValue:z10.unknown().optional(),childValue:z10.unknown().optional(),conflictingFields:z10.array(z10.string()).optional(),code:z10.object({path:z10.string(),unresolvable:z10.boolean().optional(),reason:z10.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z10.object({field:z10.string(),choice:z10.enum(["parent","child","pick","ai-pick"]),pickedValue:z10.unknown().optional(),aiSessionId:z10.string().optional()}),conflictResolutionSchema=z10.object({surface:branchSurfaceSchema,key:z10.string(),choice:z10.enum(["parent","child","pick"]),pickedValue:z10.unknown().optional(),fieldPicks:z10.array(fieldPickSchema).optional()}),mergeResultSchema=z10.object({ok:z10.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z10.array(z10.object({surface:branchSurfaceSchema,count:z10.number().int().nonnegative()})),conflicts:z10.array(conflictSchema).optional(),summary:z10.string().optional()}),mergeHydrationSchema=z10.object({mergeId:uuidSchema,conflicts:z10.array(conflictSchema),draftResolutions:z10.array(conflictResolutionSchema),status:z10.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z10.object({content:z10.string(),sha:z10.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z10.object({path:z10.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,includeDeleted:z10.boolean().optional(),includeAgentBranches:z10.boolean().optional()}).strict(),outputSchema:z10.object({data:z10.array(branchSchema)}),buildRequest:__name(({projectId,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId,from,name})=>({method:"POST",path:managementProjectPath(projectId,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z10.object({branch:branchSchema,conflicts:z10.number().int().nonnegative()}),buildRequest:__name(({projectId,branch,from})=>({method:"POST",path:managementBranchPath(projectId,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z10.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z10.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z10.unknown(),buildRequest:__name(({projectId,branch})=>({method:"DELETE",path:managementBranchPath(projectId,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z10.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z10.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,path:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId,branch,path:path53,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path53,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,collection:z10.string().min(1),rowId:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,locale:z10.string().min(1),key:z10.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,formName:z10.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z10.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z10.array(conflictResolutionSchema)}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectMergeResult},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z10.object({ok:z10.boolean()}),buildRequest:__name(({projectId,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z10.object({ok:z10.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId,branch,from})=>({method:"GET",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z10.array(conflictResolutionSchema)}).strict(),outputSchema:z10.object({mergeId:uuidSchema,lastEditedAt:z10.string()}),buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z10.object({mergeId:uuidSchema,lastEditedAt:z10.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z10.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z10.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId,branch,from,path:path53})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path53})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z11}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common();projectDomainSchema=z11.object({id:z11.string(),hostname:z11.string(),status:z11.string(),ssl:z11.record(z11.string(),z11.unknown()),cnameTarget:z11.string(),apexTargets:z11.array(z11.string()),dnsAutoConfigured:z11.boolean(),createdAt:z11.unknown(),provider:z11.enum(["cloudflare","saas_custom_domains"]),domainType:z11.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z11.object({id:uuidSchema,domain:z11.string(),status:z11.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z11.enum(["fimo","external"]),autoRenew:z11.boolean(),paymentStatus:z11.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z11.string().nullable()}).passthrough(),domainSearchResultSchema=z11.object({domain:z11.string(),available:z11.boolean(),premium:z11.boolean(),price:z11.number().nullable(),renewalPrice:z11.number().nullable(),purchaseType:z11.string().nullable()}).passthrough(),domainPricingSchema=z11.object({domain:z11.string(),price:z11.number().nullable(),renewalPrice:z11.number().nullable(),premium:z11.boolean(),allowedYears:z11.array(z11.number().int().positive())}).passthrough(),projectPath=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z11.object({}).strict(),outputSchema:z11.object({domainPurchaseEnabled:z11.boolean(),publicationDomain:z11.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,slug:z11.string().min(1).max(63)}).strict(),outputSchema:z11.object({subdomain:z11.string(),subdomainUpdatedAt:z11.string()}),buildRequest:__name(({projectId,slug})=>({method:"PATCH",path:projectPath(projectId,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z11.object({projectId:uuidSchema,base:z11.string().min(1).max(63).optional(),max:z11.number().int().positive().optional()}).strict(),outputSchema:z11.array(z11.string()),buildRequest:__name(({projectId,base,max})=>({method:"GET",path:addQuery(projectPath(projectId,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z11.object({data:z11.object({suggestions:z11.array(z11.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z11.object({projectId:uuidSchema}).strict(),outputSchema:z11.array(projectDomainSchema),buildRequest:__name(({projectId})=>({method:"GET",path:projectPath(projectId,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,hostname:z11.string().min(1).max(255),redirectToWww:z11.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,domainId:z11.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,domainId})=>({method:"POST",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site.",accessScope:"write",effect:"mutation",inputSchema:z11.object({projectId:uuidSchema,domainId:z11.string().min(1)}).strict(),outputSchema:z11.unknown(),buildRequest:__name(({projectId,domainId})=>({method:"DELETE",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z11.object({keyword:z11.string().min(1).max(100),tldFilter:z11.array(z11.string().min(1)).optional()}).strict(),outputSchema:z11.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z11.object({domain:z11.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z11.object({organizationId:z11.string().min(1)}).strict(),outputSchema:z11.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z11.object({organizationId:z11.string().min(1),domain:z11.string().min(1).max(255),years:z11.number().int().min(1).max(10).optional(),autoRenew:z11.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z11.object({organizationId:z11.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z12}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema.parse(body))}var EntryDTOSchema,PaginatedEntriesDTOSchema,EntryResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,BulkCreateEntriesResponseSchema,BulkUpdateEntriesResponseSchema,BulkDeleteEntriesResponseSchema,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common();EntryDTOSchema=z12.object({id:z12.string(),entryId:z12.string(),documentId:z12.string(),slug:z12.string(),locale:z12.string().optional(),createdAt:z12.string(),updatedAt:z12.string(),__fimo:z12.object({contentType:z12.string()})}).passthrough(),PaginatedEntriesDTOSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({limit:z12.number(),offset:z12.number(),total:z12.number(),hasMore:z12.boolean()})}),EntryResponseSchema=createResponseSchema(EntryDTOSchema),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z12.union([z12.string(),z12.number(),z12.boolean(),z12.null()]),entryWhereOperatorSchema=z12.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z12.array(entryWhereScalarSchema).optional(),$nin:z12.array(entryWhereScalarSchema).optional(),$contains:z12.string().optional(),$startsWith:z12.string().optional(),$null:z12.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z12.record(z12.string(),z12.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z12.record(z12.string(),z12.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z12.object({data:z12.record(z12.string(),z12.unknown()),locale:z12.string().min(1).optional(),documentId:z12.uuid().optional()}),BulkCreateEntriesResponseSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({created:z12.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({updated:z12.number().int().nonnegative(),missing:z12.array(z12.string())})}),BulkDeleteEntriesResponseSchema=z12.object({data:z12.array(EntryDTOSchema),meta:z12.object({deleted:z12.number().int().nonnegative(),missing:z12.array(z12.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema),typeNameSchema=z12.string().min(1).max(255),localeSchema=z12.string().min(1),populateSchema=z12.array(z12.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema.shape.data,entryResponseSchema=EntryResponseSchema,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z12.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,search:z12.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z12.string().min(1).max(255),data:entryDataSchema,locale:z12.string().min(1).optional(),documentId:z12.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z12.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z12.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z12.record(z12.string(),z12.unknown())}).strict(),outputSchema:z12.unknown(),buildRequest:__name(({projectId,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z12.object({data:z12.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,sql:z12.string().min(1)}).strict(),outputSchema:z12.object({data:z12.array(z12.record(z12.string(),z12.unknown())),meta:z12.object({rowCount:z12.number().int().nonnegative(),truncated:z12.boolean()})}),buildRequest:__name(({projectId,branch,sql})=>({method:"POST",path:tenantPath(projectId,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z12.array(z12.unknown()).max(MAX_BULK_ENTRIES)}).strict(),outputSchema:BulkCreateEntriesResponseSchema,buildRequest:__name(({projectId,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z12.union([z12.object({ids:z12.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES)}),z12.object({where:EntryWhereSchema}),z12.object({updates:z12.array(z12.object({id:uuidSchema,body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema,buildRequest:__name(({projectId,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z12.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z12.union([z12.object({ids:z12.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES)}),z12.object({where:EntryWhereSchema})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema,buildRequest:__name(({projectId,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z13}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common();productionEnvironmentSchema=z13.object({id:z13.literal("production"),projectId:uuidSchema,name:z13.string(),kind:z13.literal("production"),sourceBranch:z13.string().min(1),isPublished:z13.boolean(),url:z13.string().nullable()}),previewEnvironmentSchema=z13.object({id:z13.literal("preview"),projectId:uuidSchema,name:z13.string(),kind:z13.literal("preview"),matchedBranchCount:z13.number().int().nonnegative()}),customEnvironmentSchema=z13.object({id:uuidSchema,projectId:uuidSchema,name:z13.string().min(1).max(64),branchPatterns:z13.array(z13.string().min(1).max(255)).min(1),description:z13.string().max(255).nullable(),kind:z13.literal("custom"),matchedBranchCount:z13.number().int().nonnegative()}),environmentSchema=z13.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z13.string().trim().min(1).max(64),branchPatterns:z13.array(z13.string().min(1).max(255)).min(1),description:z13.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z13.object({projectId:uuidSchema}).strict(),outputSchema:z13.array(environmentSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/environments")}),"buildRequest"),projectOutput:__name(body=>z13.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z13.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z13.object({projectId:uuidSchema,environmentId:z13.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z13.object({projectId:uuidSchema,environmentId:z13.string().min(1)}).strict(),outputSchema:z13.object({deletedId:uuidSchema}),buildRequest:__name(({projectId,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z13.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z14}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common();fileReadOutputSchema=z14.object({data:z14.object({path:z14.string(),content:z14.string(),totalLines:z14.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z14.object({data:z14.object({paths:z14.array(z14.string().min(1)).max(2e3),truncated:z14.boolean()})}),fileGrepOutputSchema=z14.object({data:z14.object({matches:z14.array(z14.object({path:z14.string().min(1),line:z14.number().int().positive(),text:z14.string()})).max(200),truncated:z14.boolean()})}),fileWriteInputSchema=z14.object({projectId:uuidSchema,sessionId:uuidSchema,path:z14.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte write limit.`),overwrite:z14.boolean().optional()}).strict(),fileEditInputSchema=z14.object({projectId:uuidSchema,sessionId:uuidSchema,path:z14.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte edit limit.`),replaceAll:z14.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z14.object({path:z14.string(),created:z14.boolean(),tip:z14.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z14.object({projectId:uuidSchema,sessionId:uuidSchema,files:z14.array(z14.object({path:z14.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files=>files.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z14.array(z14.object({path:z14.string(),created:z14.boolean()}).passthrough()),tip:z14.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z14.object({path:z14.string(),replacements:z14.number().int().nonnegative(),tip:z14.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z14.object({path:z14.string(),deleted:z14.literal(!0),tip:z14.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z14.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z14.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId,branch,sessionId,path:path53})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path53})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z14.object({...fileSearchInputShape,pattern:z14.string().min(1).max(300).optional(),limit:z14.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z14.object({...fileSearchInputShape,pattern:z14.string().min(1).max(200),include:z14.string().min(1).max(300).optional(),caseInsensitive:z14.boolean().optional(),maxMatches:z14.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path53,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path53,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId,sessionId,files})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId,sessionId,path:path53,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path53,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z14.object({projectId:uuidSchema,sessionId:uuidSchema,path:z14.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path53})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path53}}),"buildRequest")}}}});import{z as z15}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z15.object({data:z15.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z15.object({data:z15.array(formSubmissionSchema),total:z15.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page.data.length===0&&offset<page.total)throw new Error("Expected a page that advances the cursor.");return{items:page.data,nextCursor:offset+page.data.length<page.total?encodePaginationCursor(offset+page.data.length):null,total:page.total}}var formFieldSchema,FormContentSchema,FormUpdateSchema,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common();formFieldSchema=z15.object({type:z15.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z15.string(),placeholder:z15.string().optional(),required:z15.boolean().optional(),defaultValue:z15.string().optional(),options:z15.array(z15.string()).optional(),validation:z15.object({minLength:z15.number().optional(),maxLength:z15.number().optional(),min:z15.number().optional(),max:z15.number().optional(),pattern:z15.string().optional(),maxFileSize:z15.number().optional(),accept:z15.array(z15.string()).optional()}).optional()}),FormContentSchema=z15.object({name:z15.string().min(1).max(255),label:z15.string().min(1).max(255),fields:z15.record(z15.string(),formFieldSchema)}).strict(),FormUpdateSchema=FormContentSchema.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."}),rawFormSchema=z15.object({id:uuidSchema,name:FormContentSchema.shape.name,label:FormContentSchema.shape.label,fields:FormContentSchema.shape.fields,settings:z15.record(z15.string(),z15.unknown()).nullable().optional(),createdAt:z15.string(),updatedAt:z15.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z15.object({data:formSchema}),formSubmissionSchema=z15.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z15.record(z15.string(),z15.unknown()),submittedAt:z15.string()}),formSubmissionResponseSchema=z15.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z15.object({data:z15.object({total:z15.number().int().nonnegative(),dailyCounts:z15.array(z15.object({date:z15.string(),count:z15.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z15.array(formSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),...FormContentSchema.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue of update.error.issues)context.addIssue({...issue,path:issue.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),...paginationShape,searchQuery:z15.string().max(200).optional(),sortDirection:z15.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),submissionId:z15.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z15.object({projectId:uuidSchema,branch:branchNameSchema,id:z15.string().min(1).max(255),submissionId:z15.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z16}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common();estimateSchema=z16.object({costUsd:z16.number(),credits:z16.number().optional(),billingMode:z16.enum(["fimo-credits","provider-account"]).optional(),confidence:z16.enum(["exact","estimated","metered"]),basis:z16.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z16.object({projectId:uuidSchema,model:z16.string().min(1),options:z16.record(z16.string(),z16.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z16.object({projectId:uuidSchema,branch:branchNameSchema,task:z16.string().min(1),options:z16.record(z16.string(),z16.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,branch,task,options})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z17}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common();historyKindSchema=z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z17.object({versionId:uuidSchema,commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:historyKindSchema,createdAt:z17.iso.datetime(),expiresAt:z17.iso.datetime()}),projectVersionPageSchema=z17.object({items:z17.array(projectVersionSchema),nextCursor:z17.string().nullable()}),historySummarySchema=z17.object({usage:z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),retentionDays:z17.number().int().positive()}),restoreResultSchema=z17.object({durationMs:z17.number().nonnegative().optional(),warning:z17.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,limit:z17.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/versions"),{limit,cursor})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,name:z17.string().min(1),description:z17.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z17.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z18}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page.items.map(publicationRecord),nextCursor:page.nextCursor,retention:page.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z18.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z18.object({isPublished:z18.boolean(),publishedAt:z18.iso.datetime().nullable(),publishedVersion:z18.string().nullable()}),publicationOutputSchema=z18.object({id:uuidSchema,status:z18.enum(["queued","building","published","failed","canceled"]),label:z18.string().nullable(),notes:z18.string().nullable(),source:z18.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z18.string().nullable(),framework:z18.string().nullable(),commit:z18.string().nullable()}),createdAt:z18.iso.datetime(),finishedAt:z18.iso.datetime().nullable(),url:z18.string().nullable(),failureCode:z18.string().nullable()}),publicationsPageOutputSchema=z18.object({items:z18.array(publicationOutputSchema),nextCursor:z18.string().nullable(),retention:z18.object({scope:z18.literal("publication_attempt_record"),records:z18.literal("project_lifetime")})}),publicationLogsOutputSchema=z18.object({status:z18.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z18.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z18.string().nullable(),items:z18.array(z18.object({timestamp:z18.iso.datetime(),phase:z18.enum(["build","deploy"]),stream:z18.enum(["command","stdout","stderr","status","error"]),message:z18.string()}))}),sandboxLogsOutputSchema=z18.object({status:z18.enum(["ok","unavailable"]),reason:z18.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z18.string().nullable(),items:z18.array(z18.object({id:z18.string(),timestamp:z18.iso.datetime().nullable(),source:z18.enum(["install","dev-server"]),phase:z18.string(),stream:z18.enum(["combined","stdout","stderr"]),message:z18.string()})),nextCursor:z18.string().nullable(),retention:z18.object({scope:z18.literal("sandbox_process_snapshot"),timestamps:z18.literal("process_start"),droppedOldest:z18.boolean(),phases:z18.array(z18.object({phase:z18.string(),source:z18.enum(["install","dev-server"]),status:z18.string(),startedAt:z18.iso.datetime().nullable(),exitCode:z18.number().int().nullable(),events:z18.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z18.object({url:z18.string(),branch:branchNameSchema}),previewOpenOutputSchema=z18.object({url:z18.url(),expiresAt:z18.iso.datetime().nullable()}),publishOutputSchema=z18.object({success:z18.boolean(),message:z18.string().optional(),firstPublish:z18.boolean(),publicationId:z18.string().optional(),url:z18.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,limit:z18.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,publicationId:z18.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId,publicationId})=>({method:"GET",path:managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z18.object({projectId:uuidSchema,label:z18.string().trim().min(1).max(120).optional(),notes:z18.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId,label,notes})=>({method:"POST",path:managementProjectPath(projectId,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,publicationId:z18.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/sandbox/logs"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z18.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z18.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z19}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common();knowledgeSchema=z19.object({content:z19.string(),updatedAt:z19.string().nullable(),updatedBy:z19.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z19.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance.",accessScope:"write",effect:"mutation",inputSchema:z19.object({projectId:uuidSchema,content:z19.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId,content:content2})=>({method:"PUT",path:managementProjectPath(projectId,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z20}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common();init_entries();TranslationDTOSchema=z20.object({key:z20.string(),value:z20.string().optional(),defaultValue:z20.string(),locale:z20.string()}),labelResponseSchema=createResponseSchema(TranslationDTOSchema),labelListOutputSchema=z20.object({data:z20.array(z20.union([TranslationDTOSchema,z20.object({key:z20.string(),values:z20.record(z20.string(),z20.string())})]))}),labelUpsertOutputSchema=z20.object({created:z20.number().int().nonnegative(),updated:z20.number().int().nonnegative(),deleted:z20.number().int().nonnegative(),defaultLocale:z20.string(),locales:z20.array(z20.string())}),labelDeleteOutputSchema=z20.object({key:z20.string(),locale:z20.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z20.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"GET",path:tenantPath(projectId,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,key:z20.string(),value:z20.string(),locale:z20.string().optional()}).strict(),outputSchema:TranslationDTOSchema,buildRequest:__name(({projectId,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,records:z20.array(z20.object({key:z20.string(),value:z20.string(),locale:z20.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId,branch,records})=>({method:"POST",path:tenantPath(projectId,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z20.object({projectId:uuidSchema,branch:branchNameSchema,locale:z20.string().optional(),key:z20.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z21}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleResponseSchema,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common();projectLocaleCoverageSchema=z21.object({translated:z21.number().int().nonnegative(),total:z21.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema=createResponseSchema(z21.object({defaultLocale:z21.string(),locales:z21.array(z21.object({locale:z21.string(),isDefault:z21.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z21.string().min(1).max(40),ProjectLocaleMutationResponseSchema=createResponseSchema(z21.object({locale:z21.string()})),RemoveProjectLocaleResponseSchema=createResponseSchema(z21.object({locale:z21.string(),entriesDeleted:z21.number().int().nonnegative(),labelsDeleted:z21.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"POST",path:managementBranchPath(projectId,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z21.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z22}from"zod";var agentQuestionSchema,projectPath2,notificationsOperations,init_notifications=__esm({"../../packages/sdk/dist/operations/notifications.js"(){"use strict";init_common();agentQuestionSchema=z22.object({id:uuidSchema,projectId:uuidSchema,threadId:uuidSchema,invocationId:uuidSchema,agentKey:z22.string(),anchorEnv:z22.string(),retainedEnv:z22.string(),state:z22.enum(["open","answered","expired","cancelled","superseded"]),request:z22.record(z22.string(),z22.unknown()),answer:z22.unknown().nullable(),askedAt:z22.iso.datetime(),expiresAt:z22.iso.datetime(),closedAt:z22.iso.datetime().nullable()}).passthrough(),projectPath2=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),notificationsOperations={"questions.get":{domain:"notifications",summary:"Read the decision form attached to an agent question.",accessScope:"read",effect:"read",inputSchema:z22.object({projectId:uuidSchema,questionId:uuidSchema}).strict(),outputSchema:agentQuestionSchema,buildRequest:__name(({projectId,questionId})=>({method:"GET",path:projectPath2(projectId,`/questions/${encodeURIComponent(questionId)}`)}),"buildRequest"),projectOutput:responseData},"questions.answer":{domain:"notifications",summary:"Answer an agent question and continue its retained run.",accessScope:"write",effect:"mutation",inputSchema:z22.object({projectId:uuidSchema,questionId:uuidSchema,answer:z22.record(z22.string(),z22.unknown())}).strict(),outputSchema:z22.object({question:agentQuestionSchema,continuationInvocationId:uuidSchema,deduped:z22.boolean()}),buildRequest:__name(({projectId,questionId,answer})=>({method:"POST",path:projectPath2(projectId,`/questions/${encodeURIComponent(questionId)}/answer`),body:answer}),"buildRequest"),projectOutput:responseData}}}});import{z as z23}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common();organizationSchema=z23.object({id:z23.string().min(1),name:z23.string(),slug:z23.string()}),organizationMemberSchema=z23.object({id:z23.string().min(1),role:z23.string(),createdAt:z23.string().optional(),user:z23.object({id:z23.string().min(1),name:z23.string().nullable().optional(),email:z23.string().nullable().optional()}).optional()}),organizationInvitationSchema=z23.object({id:z23.string().min(1),email:z23.email(),role:z23.string(),organizationId:z23.string().min(1),inviterId:z23.string().min(1),status:z23.string(),expiresAt:z23.string(),createdAt:z23.string()}).passthrough(),referralSummarySchema=z23.object({counts:z23.object({signed_up:z23.number().int(),activated:z23.number().int()}),credits:z23.object({total:z23.number().int(),earned:z23.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z23.object({}).strict(),outputSchema:createResponseSchema(z23.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z23.object({organizationId:z23.string().min(1)}).strict(),outputSchema:z23.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z23.object({members:z23.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z23.object({organizationId:z23.string().min(1),email:z23.email(),role:z23.enum(["owner","admin","member"]),resend:z23.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z23.object({userId:z23.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z24}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common();projectSchema=z24.object({id:uuidSchema,name:z24.string(),displayName:z24.string().nullable(),organizationId:z24.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z24.string().optional(),appUrl:z24.string().nullable().optional(),previewEnabled:z24.boolean().optional()}).passthrough(),projectResponseSchema=z24.object({data:projectSchema}),transferResultSchema=z24.object({projectId:z24.string(),sourceOrganizationId:z24.string(),targetOrganizationId:z24.string(),movedThreads:z24.number().int().nonnegative(),revokedInvites:z24.number().int().nonnegative(),revokedGrants:z24.number().int().nonnegative(),preservedGrants:z24.number().int().nonnegative(),warnings:z24.array(z24.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z24.object({organizationId:z24.string().min(1).optional()}).strict(),outputSchema:z24.object({data:z24.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z24.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z24.object({organizationId:z24.string().min(1),displayName:z24.string().min(1).optional(),origin:z24.enum(["scratch","migration"]).optional(),starter:z24.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,targetOrganizationId:z24.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,email:z24.email(),role:z24.enum(["full","edit","comment","view"])}).strict(),outputSchema:z24.object({id:z24.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z24.object({id:z24.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema}).strict(),outputSchema:z24.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z25}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common();dateSchema=z25.iso.datetime(),scheduleStatusSchema=z25.enum(["ok","failed"]),runStatusSchema=z25.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z25.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z25.string().min(1),name:z25.string().min(1),cron:z25.string().min(1),command:z25.string().min(1),secretKeys:z25.array(z25.string().min(1)),enabled:z25.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z25.string().nullable(),overPolicyReasons:z25.array(z25.string()).optional()}).passthrough(),usageSchema=z25.object({runCount:z25.number().int().nonnegative(),runsWithOutput:z25.number().int().nonnegative()}),policySchema=z25.object({maxRuns:z25.number().int().positive(),retentionDays:z25.number().int().positive().nullable(),outputRetentionDays:z25.number().int().positive(),maxOutputBytes:z25.number().int().positive()}).passthrough(),planSchema=z25.object({code:z25.enum(["Free","PAYG","Premium","Pro"]),source:z25.enum(["cached_subscription","free_fallback"]),activeSchedules:z25.object({used:z25.number().int().nonnegative(),limit:z25.number().int().positive()}),minCadenceMinutes:z25.number().int().positive(),maxRunMs:z25.number().int().positive(),concurrency:z25.object({used:z25.number().int().nonnegative(),limit:z25.number().int().positive()}),compute:z25.object({settledMs:z25.number().int().nonnegative(),activeMs:z25.number().int().nonnegative(),reservedMs:z25.number().int().nonnegative().optional(),includedMs:z25.number().int().positive(),remainingMs:z25.number().int().nonnegative(),resetsAt:dateSchema}),state:z25.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z25.array(z25.string())}).passthrough(),runSchema=z25.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z25.string().min(1),scheduleName:z25.string().min(1),command:z25.string().min(1),status:runStatusSchema,trigger:z25.enum(["cron","ui","cli"]),triggeredBy:z25.object({id:z25.string().min(1),name:z25.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z25.number().int().nullable(),errorCode:z25.string().nullable(),error:z25.string().nullable(),outputBytes:z25.number().int().nonnegative(),outputTruncated:z25.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z25.string().nullable(),secretSnapshot:z25.object({state:z25.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z25.array(z25.object({key:z25.string().min(1),updatedAt:dateSchema.nullable(),resolution:z25.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z25.object({items:z25.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z25.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z25.object({items:z25.array(runSchema),nextCursor:z25.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z25.string().min(1).max(120),cron:z25.string().min(1).max(120),command:z25.string().min(1).max(500),secretKeys:z25.array(z25.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape}).strict(),outputSchema:z25.array(scheduleSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z25.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,...scheduleWriteShape,enabled:z25.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z25.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z25.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z25.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z25.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z25.object({ok:z25.literal(!0)}),buildRequest:__name(({projectId,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z25.object({ok:z25.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z26}from"zod";function projectSchemaDefinition(body){return z26.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common();contentTypeSchema=z26.object({id:z26.string(),name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),slugUnique:z26.boolean(),i18n:z26.record(z26.string(),z26.unknown()),groups:z26.array(z26.record(z26.string(),z26.unknown())),fields:z26.record(z26.string(),z26.unknown()),createdAt:z26.string(),updatedAt:z26.string()}).passthrough(),schemaListOutputSchema=z26.object({contentTypes:z26.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z26.object({typeName:z26.string().min(1).max(255),generatedPaths:z26.array(z26.string().min(1)).max(1e3),tip:z26.string().min(1)})}),schemaDefinitionInputSchema=z26.record(z26.string(),z26.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z26.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId,branch,typeName})=>({method:"GET",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z26.array(schemaDefinitionInputSchema).min(1).max(100),operations:z26.array(z26.record(z26.string(),z26.unknown())).optional()}).strict(),outputSchema:z26.array(z26.unknown()),buildRequest:__name(({projectId,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z26.object({data:z26.array(z26.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z26.string().min(1).max(255)}).strict(),outputSchema:z26.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z26.object({data:z26.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z26.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z26.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z26.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z26.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z27}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common();environmentSchema2=z27.union([z27.literal("production"),z27.literal("preview"),uuidSchema]),secretKindSchema=z27.enum(["variable","secret"]),projectSecretSchema=z27.object({id:z27.string().min(1),projectId:z27.string().min(1),key:z27.string().min(1),kind:secretKindSchema,exposure:z27.enum(["public","private"]),environment:environmentSchema2,value:z27.string().optional(),maskedValue:z27.string().optional(),createdAt:z27.string(),updatedAt:z27.string()}),secretWriteInputSchema=z27.object({projectId:uuidSchema,key:z27.string().min(1).max(255),kind:secretKindSchema,value:z27.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z27.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z27.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z27.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z27.object({projectId:uuidSchema,key:z27.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z27.unknown(),buildRequest:__name(({projectId,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z27.object({projectId:uuidSchema,branch:z27.string().min(1)}).strict(),outputSchema:z27.object({branch:z27.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z27.array(z27.object({branch:z27.string().optional(),env:z27.string().optional(),parentBranch:z27.string().nullable().optional(),parentEnv:z27.string().nullable().optional(),resolvedEnvironment:z27.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z28}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,resolvedMergeStrategySchema,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z28.object({status:z28.literal("passed")}).passthrough(),sessionConflictSummarySchema=z28.object({surface:surfaceNameSchema,key:z28.string().min(1),kind:z28.string().optional(),description:z28.string(),path:z28.string().optional()}).passthrough(),surfaceDeltaItemSchema=z28.object({verb:z28.enum(["added","removed","changed","conflict"]),key:z28.string(),detail:z28.string().optional(),origin:z28.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z28.record(z28.string(),z28.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z28.object({surface:surfaceNameSchema,status:z28.enum(["ok","timed_out","failed","unchanged"]),durationMs:z28.number().int().nonnegative().optional(),changedCount:z28.number().int().nonnegative(),conflictCount:z28.number().int().nonnegative(),items:z28.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z28.boolean().optional(),error:z28.string().optional()}).passthrough(),sessionChangesSchema=z28.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z28.iso.datetime(),surfaces:z28.array(perSurfaceDeltaSchema),crossSurface:z28.array(crossSurfaceFindingSchema).optional(),fingerprint:z28.string()}).passthrough(),projectScriptStatusSchema=z28.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z28.discriminatedUnion("operation",[z28.object({operation:z28.literal("dependencies_install"),repairedInstallPolicy:z28.boolean(),tip:z28.string()}),z28.object({operation:z28.literal("schemas_sync"),tip:z28.string()}),z28.object({operation:z28.literal("typecheck"),status:projectScriptStatusSchema,output:z28.string()}),z28.object({operation:z28.literal("lint"),status:projectScriptStatusSchema,output:z28.string()})]),conflictSchema2=z28.object({surface:surfaceNameSchema,key:z28.string(),kind:z28.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z28.string(),parentValue:z28.unknown().optional(),childValue:z28.unknown().optional(),conflictingFields:z28.array(z28.string()).optional(),code:z28.object({path:z28.string(),unresolvable:z28.boolean().optional(),reason:z28.string().optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z28.object({oid:z28.string().optional(),content:z28.string().optional(),truncated:z28.boolean(),binary:z28.boolean()}),codeConflictDetailSchema=z28.object({path:z28.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z28.string(),targetTipSha:z28.string(),mergeBaseSha:z28.string().optional()}),resolutionChoiceSchema=z28.enum(["parent","child","pick"]),conflictResolutionSchema2=z28.object({surface:surfaceNameSchema,key:z28.string().min(1),choice:resolutionChoiceSchema,pickedValue:z28.unknown().optional(),fieldPicks:z28.array(z28.object({field:z28.string().min(1),choice:resolutionChoiceSchema,pickedValue:z28.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),resolvedMergeStrategySchema=z28.object({engine:z28.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z28.enum(["ff_only","ff_prefer","merge"]),squash:z28.boolean()}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z28.string().trim().min(1).max(120).optional(),goal:z28.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z28.object({session:sessionEnvelopeSchema,adopted:z28.boolean()}),buildRequest:__name(({projectId,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z28.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z28.number().int().min(1).max(100).optional()}).strict(),outputSchema:z28.object({items:z28.array(sessionEnvelopeSchema),nextCursor:z28.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z28.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z28.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z28.object({requested:z28.literal(!0),alreadyRequested:z28.boolean(),reviewId:uuidSchema,reviewUrl:z28.url(),status:z28.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z28.string().min(1),savedRevision:z28.string().min(1),fingerprint:z28.string().min(1),visibility:z28.literal("user-visible"),retention:z28.literal("durable"),expiresAt:z28.null(),merged:z28.literal(!1),published:z28.literal(!1),links:z28.object({preview:z28.url(),changes:z28.url(),conversation:z28.url().nullable()})}),buildRequest:__name(({projectId,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z28.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z28.literal("temporary"),visibility:z28.enum(["internal","user-visible"]),expiresAt:z28.iso.datetime()}),buildRequest:__name(({projectId,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId,sessionId})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z28.string().min(1).max(100),args:z28.record(z28.string(),z28.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,action:z28.enum(["merge","discard"]),message:z28.string().max(1e3).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z28.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z28.boolean(),mergeId:uuidSchema.optional(),conflictCount:z28.number().int().nonnegative().optional(),conflicts:z28.array(sessionConflictSummarySchema).optional(),parentAdvanced:z28.boolean().optional(),code:z28.string().optional(),summary:z28.string().nullable().optional()}),buildRequest:__name(({projectId,sessionId,action,message})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z28.number().int().min(1).max(100).optional(),codePath:z28.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z28.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z28.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z28.number().int().nonnegative(),error:z28.string().nullable()}),conflicts:z28.array(conflictSchema2).max(100),nextCursor:z28.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z28.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z28.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z28.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z28.iso.datetime()}),buildRequest:__name(({projectId,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z29}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z29.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z29.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z30}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common();supportReportInputSchema=z30.object({message:z30.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z30.object({id:uuidSchema,deliveryStatus:z30.enum(["pending","delivered","failed"]),message:z30.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z30.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z31}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common();jsonObjectSchema=z31.record(z31.string(),z31.unknown()),deliveryStatusSchema=z31.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z31.object({id:uuidSchema,projectId:uuidSchema,name:z31.string(),eventType:z31.string().min(1),enabled:z31.boolean(),destination:z31.object({host:z31.string(),maskedUrl:z31.string(),kind:z31.string()}),filter:jsonObjectSchema,headers:z31.array(jsonObjectSchema),bodyTemplate:z31.unknown().nullable(),signingEnabled:z31.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z31.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z31.string().min(1),status:deliveryStatusSchema,attemptCount:z31.number().int().nonnegative(),responseStatus:z31.number().int().nullable(),createdAt:z31.iso.datetime()}).passthrough(),attemptSchema=z31.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z31.number().int().positive(),status:z31.enum(["delivering","succeeded","failed"]),createdAt:z31.iso.datetime()}).passthrough(),deliveriesPageSchema=z31.object({items:z31.array(deliverySchema),pagination:z31.object({page:z31.number().int().positive(),limit:z31.number().int().positive(),total:z31.number().int().nonnegative(),totalPages:z31.number().int().positive(),hasMore:z31.boolean()}),stats:z31.object({total:z31.number().int().nonnegative(),succeeded:z31.number().int().nonnegative(),failed:z31.number().int().nonnegative()})}),eventSchema=z31.object({type:z31.string().min(1),family:z31.string(),description:z31.string(),variables:z31.array(z31.string()),data:z31.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema}).strict(),outputSchema:z31.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z31.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema}).strict(),outputSchema:z31.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z31.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z31.object({webhook:webhookSchema,signingSecret:z31.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z31.object({webhook:webhookSchema,signingSecret:z31.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z31.unknown(),buildRequest:__name(({projectId,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z31.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z31.object({signingSecret:z31.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z31.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z31.string().nullable()}),buildRequest:__name(({projectId,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z31.object({delivery:deliverySchema,attempts:z31.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z31.object({delivery:deliverySchema,attempts:z31.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z31.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z32}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_knowledge();init_labels();init_locales();init_notifications();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...notificationsOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...agentsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z32.object({id:z32.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z32.string().min(1),summary:z32.string().min(1),accessScope:z32.enum(["read","write","code","agents"]),effect:z32.enum(["read","mutation"]),inputJsonSchema:z32.record(z32.string(),z32.unknown()),outputJsonSchema:z32.record(z32.string(),z32.unknown())}).strict(),fimoOperationManifestSchema=z32.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z32.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z32.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client();init_operations()}});import{spawnSync}from"node:child_process";import fs5 from"node:fs";import path5 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs5.existsSync(path5.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile7=defaultReadFile){try{return JSON.parse(readFile7(path5.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs5.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path5.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs5.realpathSync(input)}catch{return path5.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs5.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs5.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs5.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs5.readFileSync(path5.join(root,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path5.join(loadConfig().configDir,"auto-upgrade.lock");try{fs5.mkdirSync(path5.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs5.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs6 from"node:fs";import path6 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function getCliVersion(){try{let raw=fs6.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath3(import.meta.url),CLI_ROOT2=path6.resolve(path6.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path6.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path53,message}=issue;return`${Array.isArray(path53)&&path53.length>0?`${path53.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatError(status,text,body){if(!text)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text}async function parseError(response){let text=await response.text(),body;try{body=text?JSON.parse(text):void 0}catch{return{detail:formatError(response.status,text)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text,body),code:code2,body}}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={};try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message)}catch{}throw new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=process.env.FIMO_API_TOKEN?.trim()||requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path53,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path53}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path53,init={},options={}){let response=await send(path53,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path53,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path53,init={}){let response=await send(path53,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new Error(`API ${init.method??"GET"} ${path53} failed: ${response.status} ${error.detail}`)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path53,status,detail,code2,body){super(`API ${method} ${path53} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path53,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;constructor(apiUrl,required=[],message,server={}){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required,this.code=server.code,this.detail=server.detail}},CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});function colorEnabled(opts={}){if(opts.forceDisable)return!1;let env=opts.env??process.env;return env.NO_COLOR&&env.NO_COLOR.length>0?!1:env.FORCE_COLOR&&env.FORCE_COLOR!=="0"&&env.FORCE_COLOR!=="false"?!0:(opts.isTTY??process.stdout.isTTY??!1)===!0}function makeColorPalette(opts={}){let on=colorEnabled(opts),wrap=__name(style=>s=>on?`${ANSI[style]}${s}${ANSI.reset}`:s,"wrap");return{enabled:on,bold:wrap("bold"),dim:wrap("dim"),red:wrap("red"),green:wrap("green"),yellow:wrap("yellow"),blue:wrap("blue"),magenta:wrap("magenta"),cyan:wrap("cyan"),gray:wrap("gray")}}var ANSI,palette,init_color=__esm({"src/cli/utils/format/color.ts"(){ANSI={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};__name(colorEnabled,"colorEnabled");__name(makeColorPalette,"makeColorPalette");palette=makeColorPalette()}});function detectProjectLayout(paths){let hasCurrentProject=!1,hasLegacyProject=!1,hasCurrentMarker=!1,hasLegacyMarker=!1;for(let input of paths){let file=input.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");hasCurrentProject||=file===CURRENT_PROJECT_LAYOUT.project,hasLegacyProject||=file===LEGACY_PROJECT_LAYOUT.project,hasCurrentMarker||=file===CURRENT_PROJECT_LAYOUT.config||file===CURRENT_PROJECT_LAYOUT.agents||file.startsWith(`${CURRENT_PROJECT_LAYOUT.agents}/`),hasLegacyMarker||=file===LEGACY_PROJECT_LAYOUT.config||file===LEGACY_AGENT_POLICY_PATH}return hasCurrentProject?"current":hasLegacyProject?"legacy":hasCurrentMarker?"current":hasLegacyMarker?"legacy":null}function getProjectLayoutPaths(layout){return layout==="current"?CURRENT_PROJECT_LAYOUT:LEGACY_PROJECT_LAYOUT}function selectProjectConfigPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)&&!files.has(LEGACY_PROJECT_LAYOUT.config)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}function selectProjectPolicyPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}var CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT,LEGACY_AGENT_POLICY_PATH,init_project_layout=__esm({"src/runtime/project-layout.ts"(){CURRENT_PROJECT_LAYOUT={project:".fimo/project.json",config:".fimo/config.json",agents:".fimo/agents"},LEGACY_PROJECT_LAYOUT={project:".fimo.settings.json",config:"fimo-config.json",agents:"agents"},LEGACY_AGENT_POLICY_PATH="fimo.config.json";__name(detectProjectLayout,"detectProjectLayout");__name(getProjectLayoutPaths,"getProjectLayoutPaths");__name(selectProjectConfigPath,"selectProjectConfigPath");__name(selectProjectPolicyPath,"selectProjectPolicyPath")}});import fs7 from"node:fs";import path7 from"node:path";function existingLayoutPaths(cwd){return[CURRENT_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,CURRENT_PROJECT_LAYOUT.agents,LEGACY_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(file=>fs7.existsSync(path7.join(cwd,file)))}function detectProjectLayoutAtRoot(cwd){return detectProjectLayout(existingLayoutPaths(cwd))}function resolveProjectLayoutPaths(cwd,fallback="current"){return getProjectLayoutPaths(detectProjectLayoutAtRoot(cwd)??fallback)}function resolveProjectSettingsPath(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).project)}function resolveProjectConfigPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectConfigPath(files,detectProjectLayout(files)))}function resolveProjectPolicyPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectPolicyPath(files,detectProjectLayout(files)))}function resolveProjectAgentsDir(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).agents)}function loadProjectSettings(cwd){let settingsPath=resolveProjectSettingsPath(cwd);if(!fs7.existsSync(settingsPath))throw new Error("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project.");return JSON.parse(fs7.readFileSync(settingsPath,"utf-8"))}function findProjectRoot(start){let dir=path7.resolve(start);for(;;){if(fs7.existsSync(path7.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs7.existsSync(path7.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path7.dirname(dir);if(parent===dir)return null;dir=parent}}function resolveProjectCwd(cwdOption){let start=path7.resolve(cwdOption??process.cwd());return findProjectRoot(start)??start}var init_project=__esm({"src/cli/utils/project.ts"(){init_project_layout();__name(existingLayoutPaths,"existingLayoutPaths");__name(detectProjectLayoutAtRoot,"detectProjectLayoutAtRoot");__name(resolveProjectLayoutPaths,"resolveProjectLayoutPaths");__name(resolveProjectSettingsPath,"resolveProjectSettingsPath");__name(resolveProjectConfigPath,"resolveProjectConfigPath");__name(resolveProjectPolicyPath,"resolveProjectPolicyPath");__name(resolveProjectAgentsDir,"resolveProjectAgentsDir");__name(loadProjectSettings,"loadProjectSettings");__name(findProjectRoot,"findProjectRoot");__name(resolveProjectCwd,"resolveProjectCwd")}});import{z as z33}from"zod";function filterUnknownProperties(data,schema){if(data==null)return data;if(schema instanceof z33.ZodOptional||schema instanceof z33.ZodNullable||schema instanceof z33.ZodDefault)return filterUnknownProperties(data,schema.unwrap());if(schema instanceof z33.ZodArray){if(!Array.isArray(data))return data;let itemSchema=schema.unwrap();return data.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z33.ZodDiscriminatedUnion){if(typeof data!="object"||data===null)return data;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z33.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data,matchingSchema):data}if(schema instanceof z33.ZodObject){if(typeof data!="object")return data;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data,key)){let fieldSchema=shape[key],fieldValue2=data[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z33.ZodUnknown)for(let[key,value]of Object.entries(data))key in shape||(result[key]=value);return result}return data}function createObjectDTO(schema){return{schema,from(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z33.ZodObject)return createObjectDTO(schema);if(schema instanceof z33.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z34}from"zod";function createCursorPageDataSchema(dataSchema){return z34.object({items:z34.array(dataSchema),nextCursor:z34.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z34.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema2,createPaginatedResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema2=__name(dataSchema=>z34.object({data:dataSchema}),"createResponseSchema"),createPaginatedResponseSchema=__name(dataSchema=>z34.object({data:z34.array(dataSchema),page:z34.number(),total:z34.number(),totalPages:z34.number(),hasMore:z34.boolean()}),"createPaginatedResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z35}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z35.object({page:z35.coerce.number().int().positive().default(1),limit:z35.coerce.number().int().positive().max(100).default(20)})}});import{z as z36}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common2=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z36.coerce.date(),positiveInt:z36.number().int().positive(),nonNegativeInt:z36.number().int().nonnegative()},BaseEntitySchema=z36.object({id:z36.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z36.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z36.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z36.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z36.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z36.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z36.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z36.enum(["owner","admin","member"]),AssetTypeSchema=z36.enum(["file","folder"]),TemplateCodeSchema=z36.enum(["Free","PAYG","Premium","Pro"]),FieldTypeSchema=z36.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});import{z as z37}from"zod";var MB,MAX_UPLOAD_FILE_SIZE_BYTES,MAX_DOCUMENT_SIZE_BYTES,MAX_AUDIO_SIZE_BYTES,MAX_IMAGE_SIZE_BYTES,MAX_VIDEO_SIZE_BYTES,MAX_ARCHIVE_SIZE_BYTES,MAX_MODEL_SIZE_BYTES,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES,MODEL_MEDIA_TYPE,AttachmentModelMediaTypeSchema,MODEL_MIME_TYPES,MODEL_RENDER_VIEW_ANGLES,AttachmentModelRenderRequestSchema,AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema,AttachmentModelRenderResponseSchema,AttachmentModelRenderMeterSchema,ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";MB=1024*1024,MAX_UPLOAD_FILE_SIZE_BYTES=50*MB,MAX_DOCUMENT_SIZE_BYTES=5*MB,MAX_AUDIO_SIZE_BYTES=10*MB,MAX_IMAGE_SIZE_BYTES=20*MB,MAX_VIDEO_SIZE_BYTES=20*MB,MAX_ARCHIVE_SIZE_BYTES=20*MB,MAX_MODEL_SIZE_BYTES=20*MB,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES=20*MB,MODEL_MEDIA_TYPE={GLB:"model/gltf-binary",GLTF:"model/gltf+json",FBX:"model/fbx",OBJ:"model/obj",STL:"model/stl",PLY:"model/ply"},AttachmentModelMediaTypeSchema=z37.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z37.object({renderId:z37.uuid(),filename:z37.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z37.url()}),AttachmentModelRenderSuccessSchema=z37.object({status:z37.literal("succeeded"),views:z37.tuple([z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z37.url()}),z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z37.url()}),z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z37.url()}),z37.object({angle:z37.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z37.url()})]),elapsedMs:z37.number().nonnegative(),browserElapsedMs:z37.number().nonnegative(),diagnostics:z37.unknown().optional()}),AttachmentModelRenderFailureSchema=z37.object({status:z37.literal("failed"),error:z37.literal("render_failed"),message:z37.string(),elapsedMs:z37.number().nonnegative(),browserElapsedMs:z37.number().nonnegative()}),AttachmentModelRenderResponseSchema=z37.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z37.object({browserElapsedMs:z37.number().nonnegative()}),ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:MAX_ARCHIVE_SIZE_BYTES},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLB,extensions:[".glb"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLTF,extensions:[".gltf"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.FBX,extensions:[".fbx"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.OBJ,extensions:[".obj"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.STL,extensions:[".stl"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.PLY,extensions:[".ply"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z38}from"zod";var AssetReadRequestSchema2,AssetDerivedFileSchema,AssetReadBaseSchema,AssetReadPageSchema,AssetReadQuerySchema,AssetReadResultSchema2,init_asset_reading=__esm({"../../packages/api-contracts/dist/esm/types/asset-reading.js"(){"use strict";AssetReadRequestSchema2=z38.object({cursor:z38.string().optional(),query:z38.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),AssetDerivedFileSchema=z38.object({url:z38.url(),mediaType:z38.string(),filename:z38.string()}),AssetReadBaseSchema=z38.object({assetId:z38.uuid(),filename:z38.string(),mediaType:z38.string(),representation:z38.enum(["text","table","document","archive","image","transcript","video","model"]),content:z38.string(),derivedFiles:z38.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z38.literal("page"),start:z38.number().int().nonnegative(),end:z38.number().int().nonnegative(),total:z38.number().int().nonnegative(),nextCursor:z38.string().nullable(),complete:z38.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z38.literal("query"),query:z38.string(),source:z38.enum(["original-file","canonical-text","derived-files"]),truncated:z38.boolean()}),AssetReadResultSchema2=z38.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z39}from"zod";function isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment2(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function branchResourceKey(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${branchResourceKey(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_ANALYTICS_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_ANALYTICS_ENV_KEYS=["VITE_ENABLE_ANALYTICS","NEXT_PUBLIC_FIMO_ENABLE_ANALYTICS","NUXT_PUBLIC_FIMO_ENABLE_ANALYTICS","PUBLIC_FIMO_ENABLE_ANALYTICS"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,...FIMO_ANALYTICS_ENV_KEYS,"VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");BranchSchema=z39.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});import{z as z40}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z40.union([z40.literal(PRODUCTION_ENVIRONMENT_KEY),z40.literal(PREVIEW_ENVIRONMENT_KEY),z40.uuid()]),CustomEnvironmentSchema=z40.object({id:z40.uuid(),projectId:z40.uuid(),name:z40.string().trim().min(1).max(64),branchPatterns:z40.array(z40.string().min(1).max(255)).min(1),description:z40.string().max(255).nullable()}),ResolvedEnvironmentSchema=z40.object({branch:BranchSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});var init_realtime_room=__esm({"../../packages/api-contracts/dist/esm/types/realtime-room.js"(){"use strict";init_env()}});import{z as z41}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z41.preprocess(referenceValuePreprocess,z41.object({documentId:z41.uuid()})),ReferenceInputValueSchema=z41.preprocess(referenceValuePreprocess,z41.union([z41.object({documentId:z41.uuid()}),z41.object({slug:z41.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z41.preprocess(polymorphicReferenceValuePreprocess,z41.object({contentType:z41.string().min(1),documentId:z41.uuid()})),PolymorphicReferenceInputValueSchema=z41.preprocess(polymorphicReferenceValuePreprocess,z41.union([z41.object({contentType:z41.string().min(1),documentId:z41.uuid()}),z41.object({contentType:z41.string().min(1),slug:z41.string().min(1)})]))}});import{z as z42}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path53){let conditionPath=[...path53,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path53)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path53));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path53,fieldName,variant.uid]);else walk(field.schema.fields,[...path53,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path53,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path53,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common2();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z42.union([z42.object({field:z42.string().min(1),equals:z42.union([z42.string(),z42.number(),z42.boolean()])}).strict(),z42.object({field:z42.string().min(1),in:z42.array(z42.union([z42.string(),z42.number(),z42.boolean()])).min(1)}).strict()]),commonFieldShape={label:z42.string().min(1).optional(),description:z42.string().optional(),group:z42.union([z42.string().min(1),z42.array(z42.string().min(1)).min(1)]).optional(),editable:z42.boolean().optional(),required:z42.boolean().optional(),default:z42.unknown().optional(),showIf:z42.union([showIfClauseSchema,z42.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z42.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z42.object({...commonFieldShape,type:z42.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z42.number().optional(),max:z42.number().optional(),minLength:z42.number().int().nonnegative().optional(),maxLength:z42.number().int().nonnegative().optional(),regex:z42.string().optional(),multiple:z42.boolean().optional(),allowedMimeTypes:z42.array(z42.string()).optional(),options:z42.array(z42.string().min(1)).min(1).optional(),unique:z42.boolean().optional(),i18n:z42.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z42.object({...commonFieldShape,type:z42.literal("reference"),target:z42.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z42.array(z42.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z42.boolean().optional(),i18n:z42.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z42.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z42.record(z42.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z42.object({uid:z42.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z42.string().min(1),description:z42.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z42.object({fields:blockFieldsSchema}).strict(),blocksSchema=z42.object({oneOf:z42.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z42.object({...commonFieldShape,type:z42.literal("blocks"),min:z42.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z42.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z42.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z42.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z43}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","project_transfer","project_takedown","project_takedown_lift","organization_takedown","organization_takedown_lift","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_posthog_milestones_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_data_usage_read","ops_agent_provider_errors_read","ops_chat_history_health_read","ops_chat_history_calls_read","ops_chat_history_content_read","ops_chat_history_judge_calibration","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_intake_read","ops_pylon_queue_read","ops_support_report_change","ops_billing_read","ops_billing_agent_runtime_activate","ops_billing_entitlements_sync","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","ops_agent_branch_discard","admin_resource_read","merge_force"],AuditActionSchema=z43.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z43.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z43.enum(AUDIT_ACTOR_KINDS)}});import{z as z44}from"zod";function refineChatHistoryWindow(schema){return schema.refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"chat history windows cannot exceed 7 days"})}var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,LegacyAdoptionMutationInputSchema,LegacyAdoptionAbandonInputSchema,LegacyAdoptionActivationInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,OPS_POSTHOG_EVENTS,OPS_POSTHOG_QUESTION,OpsPosthogTimestampSchema,OpsPosthogMilestonesInputSchema,OpsPosthogFailureCodeSchema,OpsPosthogCoverageSchema,OpsPosthogCountsSchema,OpsPosthogMilestonesResponseSchema,OpsSessionHealthInputSchema,OpsProjectAnalyticsHealthInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";init_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z44.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:platform:legacy-adoption","ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:project:branch:discard","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:posthog:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z44.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:OPS_PERMISSIONS.filter(permission=>permission!=="ops:platform:legacy-adoption")},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z44.object({permissions:z44.array(OpsPermissionSchema).min(1),backendProfiles:z44.array(OpsBackendProfileSchema).min(1),enabled:z44.boolean().default(!0)}),LegacyAdoptionMutationInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3),confirmProduction:z44.boolean().default(!1)}),LegacyAdoptionAbandonInputSchema=LegacyAdoptionMutationInputSchema.extend({recordId:z44.uuid()}),LegacyAdoptionActivationInputSchema=LegacyAdoptionMutationInputSchema.extend({oldDeployment:z44.string().trim().min(1).max(200),legacyWritersStopped:z44.literal(!0)}),OpsServiceTokenInputSchema=z44.object({name:z44.string().trim().min(1).max(120),permissions:z44.array(OpsPermissionSchema).min(1),backendProfiles:z44.array(OpsBackendProfileSchema).min(1),expiresAt:z44.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z44.object({importanceReason:z44.string().trim().min(1).max(1e3),ownerUserId:z44.string().trim().min(1).nullable().optional(),framework:z44.string().trim().max(120).nullable().optional(),packageManager:z44.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z44.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z44.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z44.object({projectId:z44.uuid(),title:z44.string().trim().min(1).max(240),userReport:z44.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z44.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z44.string().trim().max(1e4).nullable().optional(),outcome:z44.string().trim().max(1e4).nullable().optional(),evidence:z44.array(z44.record(z44.string(),z44.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z44.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z44.object({fingerprint:z44.string().trim().min(1).max(240),title:z44.string().trim().min(1).max(240),description:z44.string().trim().min(1).max(1e4),affectedVersions:z44.array(z44.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z44.array(z44.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z44.string().trim().min(1).max(64).nullable().optional(),workaround:z44.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z44.array(z44.string().trim().min(1).max(120)).max(100),detectionQueries:z44.array(z44.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z44.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z44.object({changeReference:z44.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z44.string().trim().min(1).max(1e4),evidence:z44.array(z44.record(z44.string(),z44.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z44.object({recipientEmail:z44.email().optional(),subject:z44.string().trim().min(1).max(200).default("An update from Fimo"),message:z44.string().trim().min(1).max(5e3),locale:z44.string().trim().min(2).max(20),reason:z44.string().trim().min(1).max(1e3),acknowledgePolicy:z44.literal(!0)}),OpsPylonIssueIdSchema=z44.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z44.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z44.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z44.string().trim().min(1).max(255),OpsPylonEmailListSchema=z44.array(z44.email()).max(50).default([]),OpsPylonResolveInputSchema=z44.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z44.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z44.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z44.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z44.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z44.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z44.object({projectId:z44.uuid(),from:z44.coerce.date(),to:z44.coerce.date(),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z44.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z44.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z44.object({projectId:z44.uuid().optional(),organizationId:z44.string().trim().min(1).max(255).optional(),agentKey:z44.string().trim().min(1).max(120).optional(),threadId:z44.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z44.coerce.date().optional(),minCostUsd:z44.coerce.number().min(0).optional(),tracedOnly:z44.coerce.boolean().default(!1),limit:z44.coerce.number().int().min(1).max(100).default(25),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z44.object({limit:z44.coerce.number().int().min(1).max(500).default(200),reason:z44.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z44.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z44.object({maxChars:z44.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z44.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z44.object({messageIndex:z44.coerce.number().int().min(0).optional(),maxChars:z44.coerce.number().int().min(500).max(2e5).default(2e4),reason:z44.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z44.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z44.strictObject({projectId:z44.uuid().optional(),organizationId:z44.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z44.string().trim().min(1).max(120).optional(),since:z44.coerce.date(),until:z44.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z44.coerce.boolean().default(!1),limit:z44.coerce.number().int().min(1).max(200).default(50),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OPS_DATA_USAGE_MAX_WINDOW_MS=10080*60*1e3,OpsDataUsageGroupBySchema=z44.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z44.strictObject({organizationId:z44.string().trim().min(1).max(255).optional(),since:z44.coerce.date(),until:z44.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z44.coerce.number().int().min(1).max(200).default(50),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_DATA_USAGE_MAX_WINDOW_MS,{path:["since"],message:"data usage window cannot exceed 7 days"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z44.object({projectId:z44.uuid().optional(),since:z44.coerce.date(),until:z44.coerce.date().optional(),limit:z44.coerce.number().int().min(1).max(1e3).default(500),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z44.uuid().optional(),since:z44.coerce.date(),until:z44.coerce.date().default(()=>new Date),reason:z44.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z44.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z44.strictObject({...opsChatHistoryWindow,limit:z44.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z44.strictObject({...opsChatHistoryWindow,sample:z44.coerce.number().int().min(1).max(25).default(10)})),OpsChatHistoryJudgeCalibrationInputSchema=z44.strictObject({reason:z44.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z44.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z44.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z44.object({since:z44.coerce.date(),until:z44.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z44.coerce.number().min(0).optional(),limit:z44.coerce.number().int().min(1).max(200).default(50),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z44.object({since:z44.coerce.date(),until:z44.coerce.date().default(()=>new Date),model:z44.string().trim().min(1).max(120).optional(),provider:z44.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z44.coerce.date().optional(),limit:z44.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z44.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z44.boolean().default(!1),correlationLimit:z44.coerce.number().int().min(1).max(100).default(25),reason:z44.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=10080*60*1e3,{path:["since"],message:"provider error windows cannot exceed 7 days"}).refine(input=>!input.before||input.before>=input.since&&input.before<=input.until,{path:["before"],message:"before must be within the requested window"}),OpsBillingCacheInvalidateInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z44.object({reason:z44.string().trim().min(1).max(500),apply:z44.boolean().default(!1),confirmProduction:z44.boolean().default(!1),cursor:z44.string().min(1).optional(),batchSize:z44.number().int().min(1).max(100).default(50),concurrency:z44.number().int().min(1).max(10).default(2)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish","agent-branch.discard"],OpsProjectOperationKindSchema=z44.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z44.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z44.discriminatedUnion("kind",[z44.object({kind:z44.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z44.object({kind:z44.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z44.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z44.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z44.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z44.object({migrationId:OpsMigrationIdSchema,projectEnv:z44.string().trim().min(1).max(255).default("main"),reason:z44.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z44.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z44.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z44.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z44.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z44.object({pattern:z44.string().min(1).max(300).optional(),limit:z44.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z44.object({pattern:z44.string().min(1).max(200),include:z44.string().min(1).max(300).optional(),caseInsensitive:z44.boolean().default(!1),maxMatches:z44.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z44.object({path:OpsProjectFilePathSchema,content:z44.string().max(256*1024),overwrite:z44.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z44.string().trim().length(64),consentReference:z44.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z44.intersection(OpsProjectOperationPlanInputSchema,z44.object({planHash:z44.string().trim().length(64),reason:z44.string().trim().min(1).max(1e3),consentReference:z44.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z44.object({planHash:z44.string().trim().length(64),reason:z44.string().trim().min(1).max(1e3),consentReference:z44.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z44.iso.datetime({offset:!0}).refine(value=>Number.isFinite(Date.parse(value))&&!/\.\d{3}\d*[1-9]\d*(?:Z|[+-]\d{2}:\d{2})$/.test(value),"A finite timestamp with at most millisecond precision is required").transform(value=>new Date(value).toISOString()),OpsPosthogMilestonesInputSchema=z44.strictObject({projectId:z44.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z44.string().trim().min(1).max(1e3)}).refine(value=>{let duration=Date.parse(value.to)-Date.parse(value.from);return duration>0&&duration<=1440*60*1e3},{message:"Window must satisfy from < to and be at most 24 hours",path:["to"]}),OpsPosthogFailureCodeSchema=z44.enum(["not_configured","unauthenticated","forbidden","backend_mismatch","invalid_request","provider_auth_failed","provider_project_unavailable","rate_limited","timeout","provider_error","capability_unavailable","invalid_response","incomplete","pending","audit_unavailable"]),OpsPosthogCoverageSchema=z44.strictObject({completeAggregate:z44.boolean(),truncated:z44.boolean().nullable(),sampled:z44.boolean().nullable(),pagination:z44.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z44.literal(!1),providerAsOf:z44.null(),projectFilter:z44.literal("exact properties.projectId equality"),environmentFilterSupported:z44.literal(!1),excludesMissingProjectId:z44.literal(!0),transport:z44.literal("server"),consentCoverage:z44.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z44.literal(!1)}),OpsPosthogCountsSchema=z44.array(z44.strictObject({event:z44.enum(OPS_POSTHOG_EVENTS),captureCount:z44.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z44.strictObject({schemaVersion:z44.literal(1),questionId:z44.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z44.uuid().nullable(),projectEnvironment:z44.literal("mixed_or_unrecorded"),window:z44.strictObject({from:z44.iso.datetime(),to:z44.iso.datetime(),bounds:z44.literal("[from,to)")}).nullable(),source:z44.literal("posthog"),sourceStatus:z44.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z44.iso.datetime(),auditId:z44.uuid().nullable(),counts:OpsPosthogCountsSchema.nullable(),coverage:OpsPosthogCoverageSchema}).superRefine((value,ctx)=>{(value.sourceStatus==="available"?value.counts===null||value.failureCode!==null||value.auditId===null||value.projectId===null||value.window===null||!value.coverage.completeAggregate||value.coverage.sampled!==!1||value.coverage.truncated!==!1||value.coverage.pagination!=="not_applicable":value.counts!==null||value.failureCode===null||value.coverage.completeAggregate)&&ctx.addIssue({code:"custom",message:"Invalid aggregate availability"})}),OpsSessionHealthInputSchema=z44.object({reason:z44.string().trim().min(1).max(1e3),limit:z44.number().int().min(1).max(100).default(25),checkProvider:z44.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z44.object({branch:z44.string().trim().min(1).max(255),canaryPath:z44.string().max(300).regex(/^\/[a-zA-Z0-9/_-]*\?fimo_monitor=[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/).optional(),since:z44.iso.datetime({offset:!0}),until:z44.iso.datetime({offset:!0}),reason:z44.string().trim().min(1).max(1e3)}).strict().refine(input=>Date.parse(input.since)<=Date.parse(input.until),{path:["since"],message:"since must be before or equal to until"}).refine(input=>Date.parse(input.until)-Date.parse(input.since)<=10080*60*1e3,{path:["since"],message:"analytics health window cannot exceed 7 days"}).refine(input=>Date.parse(input.until)<=Date.now(),{path:["until"],message:"until cannot be in the future"}).transform(({since,until,...input})=>({...input,since:new Date(since),until:new Date(until)}))}});import{z as z45}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z45.object({kind:z45.literal("say"),label:z45.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z45.string().min(1).max(240).optional(),message:z45.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z45.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z45.discriminatedUnion("command",[z45.object({kind:z45.literal("app"),command:z45.literal("publish")}).strict(),z45.object({kind:z45.literal("app"),command:z45.literal("connect"),integrationKey:z45.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z45.object({fallback:z45.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z45.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z45.literal("choices"),text:z45.string().max(500).optional(),actions:z45.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z45.discriminatedUnion("kind",[z45.object({kind:z45.literal("entry"),collection:z45.string().min(1).max(80),entryId:z45.string().min(1).max(120)}),z45.object({kind:z45.literal("asset"),assetId:z45.string().min(1).max(120)}),z45.object({kind:z45.literal("url"),url:z45.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z45.literal("table"),columns:z45.array(z45.object({label:z45.string().min(1).max(24)})).min(2).max(4),rows:z45.array(z45.object({cells:z45.array(z45.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z45.literal("cards"),layout:z45.enum(["rail","stack"]).optional(),items:z45.array(z45.object({title:z45.string().min(1).max(60),subtitle:z45.string().min(1).max(120).optional(),imageUrl:z45.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z45.literal("entry"),label:z45.string().min(1).max(80),collection:z45.string().min(1).max(80),entryId:z45.string().min(1).max(120),path:z45.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z45.literal("assets"),items:z45.array(z45.object({url:z45.url({protocol:/^https$/}).max(2e3),alt:z45.string().min(1).max(120),label:z45.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z45.literal("callout"),title:z45.string().min(1).max(80),text:z45.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z45.literal("stat"),items:z45.array(z45.object({label:z45.string().min(1).max(24),value:z45.string().min(1).max(16),delta:z45.string().min(1).max(12).optional(),tone:z45.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z45.literal("chart"),unit:z45.string().min(1).max(12).optional(),points:z45.array(z45.object({label:z45.string().min(1).max(12),value:z45.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z45.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z45.literal("text"),placeholder:z45.string().min(1).max(120).optional(),multiline:z45.boolean().optional()}).strict(),ChatFormStepIdSchema=z45.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z45.object({id:ChatFormStepIdSchema,token:z45.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z45.string().trim().min(1).max(60),reason:z45.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z45.literal("capabilities"),items:z45.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z45.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z45.object({id:ChatFormStepIdSchema.optional(),question:z45.string().min(1).max(500),header:z45.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z45.boolean().optional(),recommended:z45.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."}),step.body.type==="capabilities"&&step.multiSelect===!1&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}).transform(step=>({...step,multiSelect:step.multiSelect??step.body.type==="capabilities"})),FormBlockSchema=BlockBaseSchema.extend({type:z45.literal("form"),steps:z45.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z45.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z45.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z45.object({stepId:ChatFormStepIdSchema.optional(),header:z45.string().min(1).max(25),question:z45.string().min(1).max(500),answer:z45.string().min(1),selectedLabels:z45.array(z45.string().min(1).max(120)).max(8),freeText:z45.string(),skipped:z45.boolean()}),ChatFormAnswerMetadataSchema=z45.object({toolCallId:z45.string().max(255).optional(),shortTitle:z45.string().max(80).optional(),questions:z45.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z45.object({version:z45.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z45.object({version:z45.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z45.string().min(1).max(255),partial:z45.boolean().optional()})}});import{z as z46}from"zod";var CHAT_PORTRAIT_SHAPES,CHAT_PORTRAIT_EYES,CHAT_PORTRAIT_MOUTHS,CHAT_PORTRAIT_COLORS,ChatPortraitSchema,init_chat_portrait=__esm({"../../packages/api-contracts/dist/esm/types/chat-portrait.js"(){"use strict";CHAT_PORTRAIT_SHAPES=["pebble","bean","cloud","drop","potato","mochi","bun","pillow"],CHAT_PORTRAIT_EYES=["dot","caret","ring","shut","small","squint"],CHAT_PORTRAIT_MOUTHS=["smile","grin","o","w"],CHAT_PORTRAIT_COLORS=["red","orange","amber","lime","emerald","teal","sky","blue","indigo","violet","fuchsia","pink"],ChatPortraitSchema=z46.object({shape:z46.enum(CHAT_PORTRAIT_SHAPES),eyes:z46.enum(CHAT_PORTRAIT_EYES),mouth:z46.enum(CHAT_PORTRAIT_MOUTHS),color:z46.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z47}from"zod";function normalizeStoredBlock(block){if(typeof block!="object"||block===null||Array.isArray(block))return block;let{type,...rest}=block;if(typeof type!="string")return block;let target=LEGACY_BLOCK_TYPES[type];return target?target==="viz"?{...rest,type:target,kind:"bar"}:{...rest,type:target}:block}function normalizeStoredBlocks(blocks){return Array.isArray(blocks)?blocks.map(normalizeStoredBlock):blocks}function normalizeStoredDocument(document){if(typeof document!="object"||document===null||Array.isArray(document))return document;let source=document;return{...source,brief:normalizeStoredBlocks(source.brief),details:normalizeStoredBlocks(source.details)}}function normalizeReportDocument(document){return document==null?null:StoredReportDocumentSchema.parse(document)}function derivedBlockBody(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"viz":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"list":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"media":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
181
181
  `)}function reportSectionContentLength(blocks){return blocks.reduce((total,block)=>total+(block.title?.length??0)+derivedBlockBody(block).length+(block.fallback?.length??0),0)}function reportBlockMarkdown(block){let parts=[];switch(block.title&&parts.push(`## ${block.title}`),block.type){case"text":parts.push(block.text);break;case"metric":parts.push(block.items.map(item=>[`**${item.value}${item.unit??""}** \u2014 ${item.label}`,item.note].filter(Boolean).join(`
182
182
  `)).join(`
183
183
 
@@ -195,7 +195,7 @@ ${block.code}
195
195
 
196
196
  `)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&&sections.push(...document.details.map(reportBlockMarkdown)),sections.join(`
197
197
 
198
- `)}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=z47.enum(REPORT_TONES),blockCommon={title:z47.string().trim().min(1).max(120).optional(),fallback:z47.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z47.object({type:z47.literal("text"),...blockCommon,text:z47.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=z47.object({type:z47.literal("metric"),...blockCommon,items:z47.array(z47.object({value:z47.string().trim().min(1).max(24),unit:z47.string().trim().min(1).max(12).optional(),label:z47.string().trim().min(1).max(160),note:z47.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z47.array(z47.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=z47.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z47.object({type:z47.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z47.string().trim().min(1).max(12).optional(),points:z47.array(z47.object({label:z47.string().trim().min(1).max(24),value:z47.number().finite(),highlight:z47.boolean().optional()}).strict()).min(2).max(24),caption:z47.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=z47.object({type:z47.literal("list"),...blockCommon,items:z47.array(z47.object({tone:ReportToneSchema.optional(),label:z47.string().trim().min(1).max(24).optional(),heading:z47.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z47.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z47.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=z47.object({type:z47.literal("table"),...blockCommon,columns:z47.array(z47.object({label:z47.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z47.array(z47.object({cells:z47.array(z47.object({text:z47.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z47.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=z47.object({type:z47.literal("media"),...blockCommon,assetId:z47.uuid(),alt:z47.string().trim().min(1).max(300),caption:z47.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=z47.object({type:z47.literal("links"),...blockCommon,items:z47.array(z47.object({label:z47.string().trim().min(1).max(120),url:z47.url({protocol:/^https$/}).max(2e3),description:z47.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z47.object({type:z47.literal("code"),...blockCommon,language:z47.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z47.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z47.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z47.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z47.object({title:z47.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z47.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z47.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=z47.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=z47.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z47.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 z48}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=z48.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z48.object({dev:z48.string().trim().min(1).optional(),build:z48.string().trim().min(1).optional(),install:z48.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z48.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z48.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z48.object({type:z48.enum(["header","cookie","query","host"]),key:z48.string().min(1).optional(),value:z48.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:z48.array(FimoHostingConditionSchema).min(1).optional(),missing:z48.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z48.object({source:z48.string().min(1),destination:z48.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z48.object({source:z48.string().min(1),destination:z48.string().min(1),permanent:z48.boolean().optional(),statusCode:z48.union([z48.literal(301),z48.literal(302),z48.literal(307),z48.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z48.object({source:z48.string().min(1),headers:z48.array(z48.object({key:z48.string().min(1),value:z48.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z48.object({rewrites:z48.array(FimoHostingRewriteSchema).optional(),redirects:z48.array(FimoHostingRedirectSchema).optional(),headers:z48.array(FimoHostingHeaderSchema).optional(),cleanUrls:z48.boolean().optional(),trailingSlash:z48.boolean().optional()}).strict(),FimoAppConfigSchema=z48.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 isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path53){return[...path53.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path53,params){return pageRouteParamNames(path53).filter(param=>!LOCALE_PARAM_NAME.test(param)&&params?.[param]?.type!=="external")}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";__name(isEntryParamBinding,"isEntryParamBinding");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 z49}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,PublishUpgradeRequiredSchema,ProjectLatestPublicationAttemptSchema,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.5","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","openai/gpt-6.1-sol","openai/gpt-6-sol","openai/gpt-6-luna","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=z49.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z49.string(),displayName:z49.string().nullable(),subdomain:z49.string().nullable().optional(),subdomainUpdatedAt:z49.date().nullable().optional(),organizationId:z49.string().nullable(),createdBy:z49.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z49.boolean().default(!0),enabledChatModels:z49.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z49.string(),thumbnailUrl:z49.string().nullable(),publishedThumbnailUrl:z49.string().nullable(),category:z49.string().nullable(),snapshotUrl:z49.string().startsWith("/").optional(),appUrl:z49.string().nullable(),lastPublishedAt:z49.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z49.object({name:z49.string().optional(),previewEnabled:z49.boolean().optional(),enabledChatModels:z49.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z49.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z49.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z49.object({id:z49.uuid(),name:z49.string(),displayName:z49.string().nullable(),thumbnailUrl:z49.string().nullable(),category:z49.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z49.object({id:z49.string(),name:z49.string(),avatar:z49.string().nullable(),color:z49.object({bg:z49.string(),text:z49.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z49.object({path:z49.string(),content:z49.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z49.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z49.object({id:z49.string(),messageId:z49.string(),versionId:z49.string().nullable(),role:ProjectChatMessageRole,parts:z49.array(z49.any()),createdAt:z49.coerce.date()}),MessageUserMetadataSchema=z49.object({id:z49.string(),name:z49.string().nullable().optional(),image:z49.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z49.number(),metadata:z49.object({user:MessageUserMetadataSchema,changeManifest:z49.array(z49.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z49.object({versionId:z49.uuid(),commitHash:z49.string(),name:z49.string(),description:z49.string().nullable(),kind:z49.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z49.object({versionCount:z49.number().int().nonnegative(),snapshotBytes:z49.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z49.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z49.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z49.object({content:z49.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z49.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z49.object({success:z49.boolean(),message:z49.string().optional(),warning:z49.string().optional(),durationMs:z49.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z49.object({code:z49.literal("PUBLISH_UPGRADE_REQUIRED"),message:z49.string(),currentVersion:z49.number().int().positive(),targetVersion:z49.literal(4)}),ProjectLatestPublicationAttemptSchema=z49.object({publicationId:z49.uuid(),status:z49.enum(["queued","building","published","failed","canceled"]),failureCode:z49.string().nullable(),sourceBranch:z49.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z49.object({isPublished:z49.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z49.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z49.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z49.object({label:z49.string().trim().min(1).max(120).optional(),notes:z49.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z49.object({success:z49.boolean(),message:z49.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z49.boolean(),publicationId:z49.string().optional(),url:z49.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z50}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=z50.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z50.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z50.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z50.string().nullable(),deletedAt:z50.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z50.object({id:z50.union([z50.literal(PREVIEW_ENVIRONMENT_KEY),z50.uuid()]),name:z50.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z50.object({sessionId:z50.uuid(),name:z50.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z50.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=z50.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z50.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z50.object({surface:z50.enum(["code","schemas","content","translations","assets","forms"]),status:z50.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z50.number().int().nonnegative(),conflictCount:z50.number().int().nonnegative()}),BranchDiffResultSchema=z50.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z50.coerce.date(),surfaces:z50.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z51}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=z51.object({projectId:z51.uuid(),name:z51.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z51.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z51.literal("production"),sourceBranch:BranchSchema,isPublished:z51.boolean(),url:z51.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z51.literal(PREVIEW_ENVIRONMENT_KEY),kind:z51.literal("preview"),matchedBranchCount:z51.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z51.literal("custom"),matchedBranchCount:z51.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z51.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z51.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z51.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z51.object({deletedId:z51.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z52}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=z52.object({kind:z52.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z52.object({kind:z52.enum(["variable","secret"]),value:z52.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z52.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z52.object({kind:z52.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z52.object({id:z52.uuid(),projectId:z52.uuid(),key:z52.string(),kind:z52.literal("secret"),exposure:z52.literal("private"),environment:EnvironmentKeySchema,maskedValue:z52.string().optional(),createdAt:z52.date().transform(value=>value.toISOString()),updatedAt:z52.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z52.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z53}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=z53.object({success:z53.literal(!0),downloadUrl:z53.string(),expiresAt:z53.string(),fileSize:z53.number(),duration:z53.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z53.object({success:z53.literal(!0),projectId:z53.string(),projectName:z53.string(),displayName:z53.string(),projectUrl:z53.string(),duration:z53.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z53.object({contentTypes:z53.number(),entries:z53.number(),assets:z53.number(),translations:z53.number(),forms:z53.number(),codeFiles:z53.number(),assetFiles:z53.number()}),ImportPreviewSurfaceDTOSchema=z53.object({name:z53.string(),included:z53.boolean(),count:z53.number().optional(),note:z53.string().optional()}),ImportPreviewDTOSchema=z53.object({projectName:z53.string(),displayName:z53.string().nullable(),category:z53.string().nullable(),exportedAt:z53.string(),version:z53.string(),envScope:z53.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z53.array(ImportPreviewSurfaceDTOSchema),fileSize:z53.number(),fileName:z53.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z53.object({success:z53.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z54}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=z54.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z54.object({type:z54.literal("manual")}),ScheduleTriggerSchema=z54.object({type:z54.literal("schedule"),cron:z54.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:z54.string().optional()}),WebhookTriggerSchema2=z54.object({type:z54.literal("webhook"),path:z54.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z54.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z55}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=z55.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z55.object({token:z55.string().min(1),risk:CapabilityRiskTierSchema,description:z55.string()}),AgentSubAgentSummarySchema=z55.object({name:z55.string().min(1),grant:z55.enum(["inherit","explicit"]),effectiveCaps:z55.array(z55.string().min(1))}),AgentInstallSummaryDTOSchema=z55.object({agentName:z55.string().min(1),env:z55.string().min(1),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z55.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z55.array(CapabilitySummaryEntrySchema),criticalCapabilities:z55.array(CapabilitySummaryEntrySchema),subAgents:z55.array(AgentSubAgentSummarySchema),declaresDelegate:z55.boolean(),cycle:z55.array(z55.string()).nullable(),missingSubAgents:z55.array(z55.string()),warnings:z55.array(z55.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z56}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemAvailabilitySchema,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=z56.object({kind:TriggerKindSchema,summary:z56.string()}),AgentListItemTriggerStateSchema=z56.object({triggerIndex:z56.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z56.boolean(),wired:z56.boolean(),syncError:z56.string().nullable()}),AgentListItemAvailabilitySchema=z56.enum(["available","pending_merge"]),AgentListItemDTOSchema=z56.object({name:z56.string().min(1),description:z56.string().nullable(),goalFirstLine:z56.string().nullable(),declaredCapabilities:z56.array(CapabilitySummaryEntrySchema),triggers:z56.array(AgentListItemTriggerSchema),triggerStates:z56.array(AgentListItemTriggerStateSchema),availability:AgentListItemAvailabilitySchema,paused:z56.boolean(),nextRunAt:z56.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z56.array(AgentListItemDTOSchema))}});import{z as z57}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,AgentDeleteResultSchema,AgentDeleteResultDTO,AgentDeleteResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z57.object({paused:z57.boolean(),cancelledRuns:z57.number().int().nonnegative(),stopIncomplete:z57.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema),AgentDeleteResultSchema=z57.object({name:z57.string(),removedFiles:z57.number().int().positive(),commitSha:z57.string().nullable(),cancelledRuns:z57.number().int().nonnegative()}),AgentDeleteResultDTO=createDTO(AgentDeleteResultSchema),AgentDeleteResultResponseSchema=createResponseSchema2(AgentDeleteResultSchema)}});import{z as z58}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=z58.object({args:z58.unknown().optional(),requestId:z58.string().min(1).max(128).optional()}),DispatchSkippedSchema=z58.object({skipped:z58.enum(["no-manual-trigger","agent-not-deployed","agent-config-invalid","manual-trigger-not-synced","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])}),DispatchAcceptedSchema=z58.object({sessionId:z58.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z58.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z59}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=z59.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z59.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z59.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z59.object({verb:SurfaceDeltaVerbSchema,key:z59.string(),detail:z59.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z59.record(z59.string(),z59.unknown()).optional()}),PerSurfaceDeltaSchema=z59.object({surface:SurfaceNameSchema,status:z59.enum(["ok","timed_out","failed","unchanged"]),durationMs:z59.number().int().nonnegative().optional(),changedCount:z59.number().int().nonnegative(),conflictCount:z59.number().int().nonnegative(),items:z59.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z59.boolean().optional(),error:z59.string().optional()}),CrossSurfaceFindingSchema=z59.object({id:z59.string(),kind:z59.string(),description:z59.string(),severity:z59.enum(["warning","error"]),source:z59.object({surface:SurfaceNameSchema,key:z59.string()}),target:z59.object({surface:SurfaceNameSchema,key:z59.string()}),actions:z59.array(z59.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z59.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z59.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z59.coerce.date(),surfaces:z59.array(PerSurfaceDeltaSchema),agents:z59.array(z59.object({id:z59.string(),name:z59.string(),status:z59.enum(["active","paused","failed"]),lastRunAt:z59.coerce.date().nullable()})).optional(),crossSurface:z59.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z59.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z59.coerce.date(),surfaces:z59.array(PerSurfaceDeltaSchema),crossSurface:z59.array(CrossSurfaceFindingSchema).optional(),fingerprint:z59.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z59.object({path:z59.string(),state:z59.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z59.string(),additions:z59.number().int().nonnegative(),deletions:z59.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z59.object({oid:z59.string().optional(),content:z59.string().optional(),truncated:z59.boolean(),binary:z59.boolean()}),CodeConflictDetailSchema=z59.object({path:z59.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z59.string(),targetTipSha:z59.string(),mergeBaseSha:z59.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z59.object({id:z59.string(),slug:z59.string(),contentType:z59.string(),data:z59.record(z59.string(),z59.unknown()),updatedAt:z59.coerce.date()}),ContentRowDiffSchema=z59.object({collection:z59.string(),rowId:z59.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z59.object({name:z59.string(),label:z59.string(),isSingleton:z59.boolean(),fields:z59.record(z59.string(),z59.unknown())}),SchemaTypeDiffSchema=z59.object({typeName:z59.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z59.object({id:z59.string(),name:z59.string(),type:z59.enum(["file","folder"]),mimeType:z59.string().nullable(),storageKey:z59.string().nullable(),url:z59.string().nullable(),fileSize:z59.number().nullable(),width:z59.number().nullable(),height:z59.number().nullable(),altText:z59.string().nullable(),caption:z59.string().nullable(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AssetDiffSchema=z59.object({assetId:z59.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z59.object({locale:z59.string(),key:z59.string(),parent:z59.string().nullable(),child:z59.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z59.object({formName:z59.string(),label:z59.string().nullable(),schemaFingerprint:z59.string(),fields:z59.record(z59.string(),z59.unknown()),settings:z59.record(z59.string(),z59.unknown()).optional()}),FormSchemaDiffSchema=z59.object({formName:z59.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=z59.enum(CONFLICT_KINDS),ConflictSchema=z59.object({surface:SurfaceNameSchema,key:z59.string(),kind:ConflictKindSchema.optional(),description:z59.string(),parentValue:z59.unknown().optional(),childValue:z59.unknown().optional(),conflictingFields:z59.array(z59.string()).optional(),code:z59.object({path:z59.string(),unresolvable:z59.boolean().optional(),reason:z59.string().optional()}).optional()}),FieldPickSchema=z59.object({field:z59.string(),choice:z59.enum(["parent","child","pick","ai-pick"]),pickedValue:z59.unknown().optional(),aiSessionId:z59.string().optional()}),ConflictResolutionSchema=z59.object({surface:SurfaceNameSchema,key:z59.string(),choice:z59.enum(["parent","child","pick"]),pickedValue:z59.unknown().optional(),fieldPicks:z59.array(FieldPickSchema).optional()}),MergeResultSchema=z59.object({ok:z59.boolean(),mergeId:z59.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z59.array(z59.object({surface:SurfaceNameSchema,count:z59.number().int().nonnegative()})),conflicts:z59.array(ConflictSchema).optional(),summary:z59.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z59.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z59.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z59.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z59.boolean().optional()}),ResolvedStrategySchema=z59.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z59.boolean()}),MergeRequestSchema=z59.object({from:BranchSchema,allowDirectMerge:z59.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z59.object({mergeId:z59.string().uuid(),streamUrl:z59.string(),strategy:ResolvedStrategySchema,acceptedAt:z59.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z59.object({mergeId:z59.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z59.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z59.array(ConflictSchema),draftResolutions:z59.array(ConflictResolutionSchema),lastEditedBy:z59.string().nullable(),lastEditedAt:z59.coerce.date().nullable(),initiator:z59.object({userId:z59.string().nullable(),role:z59.string().nullable(),agentName:z59.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z59.object({resolutions:z59.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z59.object({mergeId:z59.string().uuid(),draftResolutions:z59.array(ConflictResolutionSchema),lastEditedAt:z59.coerce.date(),lastEditedBy:z59.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z59.object({mergeId:z59.string().uuid(),resolutions:z59.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z59.object({mergeId:z59.string().uuid()}),PublishReleaseRequestSchema=z59.object({version:z59.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z59.string().max(2e4).optional()}),PublishReleaseResultSchema=z59.object({releaseTag:z59.string(),sha:z59.string(),publishedAt:z59.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z60}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentRuntimeRefusalKindSchema,AgentRunStopContextSchema,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=z60.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z60.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z60.strictObject({branch:BranchSchema.optional(),project_agents_only:z60.coerce.boolean().optional(),agent_name:z60.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z60.coerce.date().optional(),page:z60.coerce.number().int().positive().default(1),limit:z60.coerce.number().int().positive().max(200).default(25),cursor:z60.coerce.date().optional()}),SessionMetricsSchema=z60.object({cpuMs:z60.number().nonnegative().default(0),netBytes:z60.number().nonnegative().default(0),walltimeMs:z60.number().nonnegative().default(0),llmTokensIn:z60.number().nonnegative().optional(),llmTokensOut:z60.number().nonnegative().optional(),stepCount:z60.number().int().nonnegative().optional(),toolCallCounts:z60.record(z60.string().min(1).max(120),z60.number().int().nonnegative()).optional(),toolCallOutcomes:z60.array(z60.object({toolName:z60.string().min(1).max(120),success:z60.boolean(),code:z60.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z60.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z60.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z60.object({capturedAt:z60.coerce.date(),fingerprint:z60.string().min(1).max(256),counts:z60.object({code:z60.number().int().nonnegative(),content:z60.number().int().nonnegative(),schemas:z60.number().int().nonnegative(),labels:z60.number().int().nonnegative(),assets:z60.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z60.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z60.object({diff:DiffReportSchema,code:z60.array(CodeFileDiffSchema.extend({raw:z60.string().max(24576)})).max(200),schemas:z60.array(SchemaTypeDiffSchema).max(200),content:z60.array(z60.object({key:z60.string().min(1).max(512),collection:z60.string().min(1).max(256),slug:z60.string().max(512).optional(),verb:z60.enum(["added","modified","deleted"]),fields:z60.array(z60.object({name:z60.string().min(1).max(256),before:z60.unknown().optional(),after:z60.unknown().optional()})).max(20)})).max(200),labels:z60.array(z60.object({key:z60.string().min(1).max(512),locale:z60.string().min(1).max(64).optional(),before:z60.unknown().nullable(),after:z60.unknown().nullable()})).max(200),assets:z60.array(z60.object({key:z60.string().min(1).max(512),name:z60.string().min(1).max(512),verb:z60.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentRuntimeRefusalKindSchema=z60.enum(["plan_cannot_fund","consent_missing","budget_spent"]),AgentRunStopContextSchema=z60.object({kind:z60.literal("agent_runtime_allowance"),refusal:AgentRuntimeRefusalKindSchema,planCode:z60.string(),includedMs:z60.number().int().nonnegative(),resetsAt:z60.coerce.date(),rateUsdPerHour:z60.number().nullable()}),AgentSessionDTOSchema=z60.strictObject({id:z60.uuid(),projectId:z60.uuid(),branch:BranchSchema,agentName:z60.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z60.unknown().optional(),capabilities:z60.array(z60.string()).optional(),dataSources:z60.array(z60.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z60.string().nullable(),startedAt:z60.coerce.date().nullable(),finishedAt:z60.coerce.date().nullable(),cancelledAt:z60.coerce.date().nullable(),costUsd:z60.number().nonnegative(),costCeilingUsd:z60.number().nonnegative(),creditsUsed:z60.number().int().nonnegative().nullable(),limitCredits:z60.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),lastCheckpointId:z60.uuid().nullable(),agentBranchId:z60.uuid().nullable(),parentSessionId:z60.uuid().nullable(),terminalReason:z60.string().nullable(),errorMessage:z60.string().nullable(),stopContext:AgentRunStopContextSchema.nullable().catch(null),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z60.string().nullable(),retainedBranch:BranchSchema.nullable().optional(),createdAt:z60.coerce.date(),updatedAt:z60.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z60.object({id:z60.uuid(),sessionId:z60.uuid(),checkpointIdx:z60.number().int().nonnegative(),payloadRef:z60.string(),payloadSizeBytes:z60.number().int().nonnegative(),checksum:z60.string().length(64),createdAt:z60.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z60.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z60.object({session:AgentSessionDTOSchema,checkpoints:z60.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z60.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=z60.object({reason:z60.string().min(1).max(120).optional()})}});import{z as z61}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,WorkSessionReviewSchema,RequestWorkSessionReviewSchema,WorkSessionReviewResultSchema,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();init_env_status_dto();AgentBranchClassificationSchema=z61.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z61.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z61.object({sessionId:z61.uuid(),branch:z61.string().min(1),targetBranch:z61.string().min(1),revision:z61.string().min(1),fingerprint:z61.string().min(1),source:z61.enum(["studio","slack","autonomous","mcp"]),threadId:z61.uuid().nullable(),invocationId:z61.uuid().nullable(),conversationBranch:z61.string().nullable(),capturedAt:z61.string(),surfaces:z61.array(PerSurfaceDeltaSchema).optional(),counts:z61.record(z61.string(),z61.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z61.strictObject({sessionId:z61.uuid(),summary:z61.string().trim().min(1).max(240),targetBranch:z61.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z61.object({requested:z61.literal(!0),alreadyRequested:z61.boolean(),reviewId:z61.uuid(),reviewUrl:z61.url(),status:z61.literal("pending"),sessionId:z61.uuid(),branch:z61.string(),targetBranch:z61.string(),revision:z61.string(),savedRevision:z61.string(),fingerprint:z61.string(),visibility:z61.literal("user-visible"),retention:z61.literal("durable"),expiresAt:z61.null(),merged:z61.literal(!1),published:z61.literal(!1),links:z61.object({preview:z61.url(),changes:z61.url(),conversation:z61.url().nullable()})}),AgentBranchProposalDTOSchema=z61.object({id:z61.uuid(),envId:z61.uuid(),sessionId:z61.uuid().nullable(),skillName:z61.string().min(1),classification:AgentBranchClassificationSchema,rationale:z61.string().nullable(),summary:z61.string().nullable(),surfaceDeltas:z61.record(z61.string(),z61.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z61.coerce.date(),decidedAt:z61.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z61.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z61.object({path:z61.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z61.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z61.object({code:z61.literal("merge_conflict"),message:z61.string(),conflicts:z61.record(z61.string(),z61.number().int().nonnegative())})}});import{z as z62}from"zod";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=z62.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z62.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=z62.object({description:z62.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z62.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z62.array(z62.uuid()).optional()}),AgentQuestionSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),threadId:z62.uuid(),invocationId:z62.uuid(),agentKey:z62.string().min(1).max(120),anchorEnv:z62.string().min(1).max(64),retainedEnv:z62.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z62.string().min(1).nullable(),continuationInvocationId:z62.uuid().nullable(),askedAt:z62.coerce.date(),expiresAt:z62.coerce.date(),closedAt:z62.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z62.object({questionId:z62.uuid(),invocationId:z62.uuid(),askedAt:z62.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z62.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z62.object({question:AgentQuestionSchema,continuationInvocationId:z62.uuid(),deduped:z62.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z63}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=z63.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z63.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z63.enum(["secret_text"]),IntegrationCredentialUsageSchema=z63.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z63.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z63.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z63.object({mode:IntegrationAuthModeSchema,label:z63.string().min(1),description:z63.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z63.object({id:z63.string().min(1),label:z63.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z63.boolean()}),IntegrationToolDefinitionDTOSchema=z63.object({key:z63.string().min(1),name:z63.string().min(1),description:z63.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z63.object({title:z63.string().min(1),description:z63.string().min(1),command:z63.string().min(1).optional()}),IntegrationInfoDTOSchema=z63.object({key:z63.string().min(1),name:z63.string().min(1),summary:z63.string().min(1),type:z63.enum(["native","mcp"]).optional(),url:z63.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z63.array(IntegrationAuthModeDTOSchema),credentials:z63.array(IntegrationCredentialDefinitionDTOSchema),tools:z63.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z63.enum(["available","unavailable"]).optional(),connectionCapabilities:z63.object({customIdentityCreation:z63.boolean()}).optional(),recipes:z63.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z63.object({projectId:z63.uuid(),integrationKey:z63.string().min(1),name:z63.string().min(1),summary:z63.string().min(1),installed:z63.boolean(),enabled:z63.boolean(),setupState:z63.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z63.string().nullable(),connectionId:z63.uuid().nullable().optional(),connectionAlias:z63.string().min(1).nullable().optional(),connectionStatus:z63.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z63.array(z63.string()),installedAt:z63.coerce.date().nullable(),updatedAt:z63.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z63.object({id:z63.uuid(),projectId:z63.uuid(),integrationKey:z63.string().min(1),enabled:z63.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z63.string(),connectionId:z63.uuid().nullable().optional(),connectionAlias:z63.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z63.array(z63.string()),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z63.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z63.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z63.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z63.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z63.object({id:z63.uuid(),organizationId:z63.string().min(1),integrationKey:z63.string().min(1),registrationId:z63.uuid().nullable(),alias:z63.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z63.string().min(1),externalAccountName:z63.string().nullable(),externalBotUserId:z63.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z63.array(z63.string()),connectedAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z63.boolean(),isDefault:z63.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z63.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z63.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z63.record(McpHeaderNameSchema,z63.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z63.object({alias:z63.string().min(1).max(120).optional(),token:z63.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z63.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=z63.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z63.object({displayName:z63.string().trim().min(1).max(35),backgroundColor:z63.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z63.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z63.discriminatedUnion("mode",[z63.object({mode:z63.literal("personal"),alias:z63.string().min(1).max(120),token:z63.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z63.boolean().optional()}),z63.object({mode:z63.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z63.boolean().optional(),registrationId:z63.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=z63.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z63.union([z63.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z63.object({type:z63.literal("mcp"),name:z63.string().trim().min(1).max(120),url:z63.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z63.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z63.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=z63.object({integrationKey:z63.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z63.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z63.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z63.literal("oauth"),connectUrl:z63.string().url(),expiresAt:z63.coerce.date()})]),ReusableMcpServerAuthKindSchema=z63.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z63.object({id:z63.uuid(),name:z63.string().min(1),host:z63.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z63.string().min(1),availability:z63.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z63.object({query:z63.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z63.object({serverId:z63.uuid()}),LinearOAuthApplicationDistributionSchema=z63.enum(["private","public"]),OrganizationLinearAppDTOSchema=z63.object({id:z63.uuid(),displayName:z63.string().min(1),description:z63.string().nullable(),iconUrl:z63.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z63.enum(["active","revoked"]),connectionIds:z63.array(z63.uuid()),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z63.object({appName:z63.string().trim().min(2).max(80),description:z63.string().trim().max(1e3).optional(),iconUrl:z63.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z63.object({projectId:z63.uuid(),registrationId:z63.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z63.object({integrationKey:z63.string().min(1),connectUrl:z63.string().url(),expiresAt:z63.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z63.discriminatedUnion("mode",[z63.object({mode:z63.literal("personal"),integrationKey:z63.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z63.object({mode:z63.literal("oauth"),integrationKey:z63.string().min(1),connectUrl:z63.string().url(),expiresAt:z63.coerce.date()})]),BindProjectChannelRequestSchema=z63.object({ref:z63.string().min(1),connectionAlias:z63.string().min(1).optional(),agentName:z63.string().min(1).max(160).nullable().optional(),force:z63.boolean().optional()}),ListProjectChannelsQuerySchema=z63.object({integrationKey:z63.string().min(1)}),SearchProjectChannelsQuerySchema=z63.object({integrationKey:z63.string().min(1),connectionAlias:z63.string().min(1),query:z63.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z63.object({id:z63.uuid(),projectId:z63.uuid(),integrationKey:z63.string().min(1),connectionId:z63.uuid(),externalWorkspaceId:z63.string().min(1),externalChannelId:z63.string().min(1),externalChannelName:z63.string().nullable(),agentName:z63.string().nullable(),enabled:z63.boolean(),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z63.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z63.object({id:z63.string().min(1),name:z63.string().min(1),visibility:z63.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z63.string().min(1).nullable(),canMove:z63.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z63.object({markdown:z63.boolean().optional(),summary:z63.boolean().optional(),links:z63.boolean().optional(),branding:z63.boolean().optional(),images:z63.boolean().optional(),html:z63.union([z63.literal("cleaned"),z63.literal("raw"),z63.boolean()]).optional(),json:z63.union([z63.boolean(),z63.object({prompt:z63.string().min(1).max(1e4),schema:z63.record(z63.string(),z63.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z63.object({url:z63.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional(),waitForMs:z63.number().int().min(0).max(3e4).optional(),maxAgeMs:z63.number().int().min(0).optional(),minAgeMs:z63.number().int().min(0).optional(),storeInCache:z63.boolean().optional(),proxy:z63.enum(["basic","enhanced","auto"]).optional(),mobile:z63.boolean().optional(),location:z63.object({country:z63.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z63.array(z63.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z63.object({query:z63.string().min(1),maxResults:z63.number().int().positive().max(20).optional(),sources:z63.array(z63.enum(["web","news","images"])).min(1).max(3).optional(),categories:z63.array(z63.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z63.enum(["hour","day","week","month","year"]).optional(),location:z63.string().min(1).max(160).optional(),country:z63.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z63.object({query:z63.string().min(1).max(500),maxResults:z63.number().int().min(1).max(100).optional(),types:z63.array(z63.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z63.array(z63.string().min(1).max(512)).min(1).max(20).optional(),sources:z63.array(z63.string().min(1).max(512)).min(1).max(20).optional(),passages:z63.number().int().min(1).max(5).optional(),skills:z63.literal("only").optional(),language:z63.string().min(1).optional(),topic:z63.string().min(1).optional(),license:z63.string().min(1).optional(),minStars:z63.number().int().min(0).optional(),maxStars:z63.number().int().min(0).optional(),archived:z63.boolean().optional(),fork:z63.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z63.object({query:z63.string().min(1).max(500),maxResults:z63.number().int().min(1).max(500).optional(),authors:z63.array(z63.string().min(1)).min(1).optional(),categories:z63.array(z63.string().min(1)).min(1).optional(),from:z63.iso.date().optional(),to:z63.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z63.object({paperId:z63.string().min(1).max(512),query:z63.string().min(1).max(500).optional(),maxPassages:z63.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z63.object({paperId:z63.string().min(1).max(512),intent:z63.string().min(1).max(500),mode:z63.enum(["similar","citers","references"]).optional(),maxResults:z63.number().int().min(1).max(500).optional(),rerank:z63.boolean().optional(),anchors:z63.array(z63.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z63.object({url:z63.string().url(),search:z63.string().min(1).optional(),limit:z63.number().int().positive().max(200).optional(),includeSubdomains:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z63.object({url:z63.string().url(),limit:z63.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z63.object({text:z63.string().min(1).max(200).optional(),cron:z63.string().min(1).max(120).optional(),timezone:z63.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z63.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional(),waitForMs:z63.number().int().min(0).max(3e4).optional(),maxAgeMs:z63.number().int().min(0).optional(),minAgeMs:z63.number().int().min(0).optional(),storeInCache:z63.boolean().optional(),proxy:z63.enum(["basic","enhanced","auto"]).optional(),mobile:z63.boolean().optional(),location:z63.object({country:z63.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z63.array(z63.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z63.union([z63.object({type:z63.enum(["scrape","crawl"]).default("scrape"),urls:z63.array(z63.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z63.object({type:z63.literal("search"),queries:z63.array(z63.string().min(1).max(256)).min(1).max(12),searchWindow:z63.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z63.number().int().min(1).max(50).optional(),includeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z63.object({name:z63.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z63.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z63.string().min(1).max(2e3).optional(),judgeEnabled:z63.boolean().optional(),retentionDays:z63.number().int().min(1).max(365).optional(),notification:z63.object({email:z63.object({enabled:z63.boolean().default(!0),recipients:z63.array(z63.string().email()).min(1).max(20),includeDiffs:z63.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=z63.object({monitorId:z63.string().uuid(),name:z63.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z63.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z63.string().min(1).max(2e3).optional(),judgeEnabled:z63.boolean().optional(),retentionDays:z63.number().int().min(1).max(365).optional(),status:z63.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z63.object({monitorId:z63.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z63.string().uuid()}),RunProjectIntegrationToolRequestSchema=z63.object({tool:z63.string().min(1),input:z63.record(z63.string(),z63.unknown()),connectionAlias:z63.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z63.object({provider:z63.string().min(1),providerCredits:z63.number().nonnegative().optional(),providerCostUsd:z63.number().nonnegative().optional(),requests:z63.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z63.object({credits:z63.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z63.object({url:z63.string(),provider:z63.literal("firecrawl"),title:z63.string().optional(),statusCode:z63.number().optional(),markdown:z63.string().optional(),summary:z63.string().optional(),links:z63.array(z63.string()).optional(),images:z63.array(z63.string()).optional(),html:z63.string().optional(),json:z63.unknown().optional(),branding:z63.record(z63.string(),z63.unknown()).optional(),warning:z63.string().optional()}),FirecrawlSearchToolOutputSchema=z63.object({query:z63.string(),provider:z63.literal("firecrawl"),warning:z63.string().optional(),results:z63.array(z63.object({title:z63.string(),url:z63.string(),snippet:z63.string().optional(),content:z63.string().optional(),score:z63.number().optional(),publishedAt:z63.string().optional()}))}),FirecrawlResearchPaperSchema=z63.object({paperId:z63.string(),primaryId:z63.string().optional(),ids:z63.record(z63.string(),z63.array(z63.string())).optional(),title:z63.string().optional(),abstract:z63.string().optional(),score:z63.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z63.object({text:z63.string(),score:z63.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),results:z63.array(z63.object({id:z63.string(),type:z63.string().min(1).optional(),url:z63.string(),title:z63.string().optional(),passages:z63.array(z63.object({text:z63.string()}).passthrough())}).passthrough()),coverage:z63.record(z63.string(),z63.string()).optional(),reranked:z63.boolean().optional(),repos:z63.array(z63.record(z63.string(),z63.unknown())).optional(),sources:z63.array(z63.record(z63.string(),z63.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),results:z63.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),paper:z63.record(z63.string(),z63.unknown()),paperId:z63.string().optional(),query:z63.string().optional(),passages:z63.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),results:z63.array(FirecrawlResearchPaperSchema),poolSize:z63.number().int().nonnegative(),truncated:z63.boolean(),note:z63.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z63.object({url:z63.string(),provider:z63.literal("firecrawl"),count:z63.number(),links:z63.array(z63.object({url:z63.string(),title:z63.string().optional(),description:z63.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z63.object({url:z63.string(),provider:z63.literal("firecrawl"),total:z63.number(),pages:z63.array(z63.object({url:z63.string(),title:z63.string().optional(),statusCode:z63.number().optional(),markdown:z63.string().optional(),summary:z63.string().optional(),links:z63.array(z63.string()).optional(),images:z63.array(z63.string()).optional(),html:z63.string().optional(),warning:z63.string().optional()})),warning:z63.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z63.object({cron:z63.string().optional(),text:z63.string().optional(),timezone:z63.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z63.object({id:z63.string().optional(),type:z63.enum(["scrape","crawl","search"]).optional(),urls:z63.array(z63.string()).optional(),queries:z63.array(z63.string()).optional(),searchWindow:z63.string().optional(),maxResults:z63.number().optional(),includeDomains:z63.array(z63.string()).optional(),excludeDomains:z63.array(z63.string()).optional(),scrapeOptions:z63.record(z63.string(),z63.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z63.object({id:z63.string(),name:z63.string(),status:z63.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z63.string().nullable().optional(),lastRunAt:z63.string().nullable().optional(),currentCheckId:z63.string().nullable().optional(),targets:z63.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z63.string().nullable().optional(),judgeEnabled:z63.boolean().optional(),estimatedCreditsPerMonth:z63.number().optional(),createdAt:z63.string().optional(),updatedAt:z63.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z63.object({id:z63.string(),monitorId:z63.string(),scheduledFor:z63.string().nullable().optional(),startedAt:z63.string().nullable().optional(),finishedAt:z63.string().nullable().optional(),estimatedCredits:z63.number().nullable().optional(),reservedCredits:z63.number().nullable().optional(),actualCredits:z63.number().nullable().optional(),billingStatus:z63.string().nullable().optional(),summary:z63.object({totalPages:z63.number().optional(),same:z63.number().optional(),changed:z63.number().optional(),new:z63.number().optional(),removed:z63.number().optional(),error:z63.number().optional()}).passthrough().optional(),error:z63.string().nullable().optional(),createdAt:z63.string().optional(),updatedAt:z63.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitors:z63.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitorId:z63.string(),deleted:z63.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitorId:z63.string(),checks:z63.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitorId:z63.string(),check:FirecrawlMonitorCheckOutputSchema,next:z63.string().optional()}),FirecrawlToolKeySchema=z63.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=z63.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z63.object({projectId:z63.uuid(),integrationKey:z63.string().min(1),tool:z63.string().min(1),connectionAlias:z63.string().min(1).nullable().optional(),output:z63.record(z63.string(),z63.unknown()),executedAt:z63.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z63.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z63.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z63.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z63.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z63.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z63.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z63.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z63.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z63.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z63.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z63.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z63.array(ProjectChannelCandidateDTOSchema))}});import{z as z64}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=z64.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z64.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z64.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z64.object({userId:z64.string().min(1),name:z64.string(),email:z64.string().min(1),subscribed:z64.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z64.object({maxSubscribers:z64.number().int().positive(),subscriberCount:z64.number().int().nonnegative(),effectiveRecipientCount:z64.number().int().nonnegative(),currentUserSubscribed:z64.boolean(),candidates:z64.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z64.object({userIds:z64.array(z64.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z64.object({topic:UserManagedNotificationTopicSchema,enabled:z64.boolean(),source:z64.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z64.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z64.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z64.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z64.string().nullable(),maskedEmail:z64.string().min(1),applied:z64.boolean(),expiresAt:z64.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z64.object({scheduleId:z64.string().min(1),scheduleName:z64.string(),projectId:z64.string().min(1),projectName:z64.string(),env:z64.string().min(1)}),FollowedSchedulesSchema=z64.object({schedules:z64.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z65}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=z65.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=z65.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z65.uuid(),env:z65.string().min(1),name:z65.string().min(1),cron:z65.string().min(1),command:z65.string().min(1),secretKeys:z65.array(z65.string().min(1)),enabled:z65.boolean(),lastRunAt:z65.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z65.string().nullable(),suspendedAt:z65.coerce.date().nullable().optional(),suspensionReason:z65.string().nullable().optional(),overPolicyReasons:z65.array(z65.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z65.object({name:z65.string().min(1).max(120),cron:z65.string().min(1).max(120),command:z65.string().min(1).max(500),secretKeys:z65.array(ProjectSecretKeySchema).default([]),enabled:z65.boolean().optional()}),UpdateProjectScheduleRequestSchema=z65.object({name:z65.string().min(1).max(120).optional(),cron:z65.string().min(1).max(120).optional(),command:z65.string().min(1).max(500).optional(),secretKeys:z65.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z65.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z65.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z65.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z65.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z65.object({maxRuns:z65.number().int().positive(),retentionDays:z65.number().int().positive().nullable(),outputRetentionDays:z65.number().int().positive(),maxOutputBytes:z65.number().int().positive()}),SchedulePolicyStateSchema=z65.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z65.object({code:z65.enum(["Free","PAYG","Premium","Pro"]),source:z65.enum(["cached_subscription","free_fallback"]),activeSchedules:z65.object({used:z65.number().int().nonnegative(),limit:z65.number().int().nonnegative()}),minCadenceMinutes:z65.number().int().positive(),maxRunMs:z65.number().int().positive(),concurrency:z65.object({used:z65.number().int().nonnegative(),limit:z65.number().int().positive()}),compute:z65.object({settledMs:z65.number().int().nonnegative(),activeMs:z65.number().int().nonnegative(),reservedMs:z65.number().int().nonnegative().optional(),includedMs:z65.number().int().nonnegative(),remainingMs:z65.number().int().nonnegative(),resetsAt:z65.coerce.date()}),upgrade:z65.object({code:z65.literal("Pro"),activeSchedulesLimit:z65.number().int().positive(),minCadenceMinutes:z65.number().int().positive(),maxRunMs:z65.number().int().positive(),maxConcurrentRuns:z65.number().int().positive(),computeIncludedMs:z65.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z65.array(z65.string())}),ProjectScheduleUsageSchema=z65.object({runCount:z65.number().int().nonnegative(),runsWithOutput:z65.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z65.object({id:z65.uuid(),scheduleId:z65.uuid(),projectId:z65.uuid(),env:z65.string().min(1),scheduleName:z65.string().min(1),command:z65.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z65.object({id:z65.string().min(1),name:z65.string().min(1)}).nullable(),queuedAt:z65.coerce.date(),startedAt:z65.coerce.date().nullable(),finishedAt:z65.coerce.date().nullable(),exitCode:z65.number().int().nullable(),errorCode:z65.string().nullable(),error:z65.string().nullable(),outputBytes:z65.number().int().nonnegative(),outputTruncated:z65.boolean(),outputExpiresAt:z65.coerce.date().nullable(),metadataExpiresAt:z65.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z65.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z65.coerce.date().nullable(),items:z65.array(z65.object({key:z65.string().min(1),updatedAt:z65.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z65.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z65.object({trigger:z65.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z65.object({limit:z65.coerce.number().int().min(1).max(100).default(25),cursor:z65.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z65.object({items:z65.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z65.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z65.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z65.object({items:z65.array(ProjectScheduleRunDTOSchema),nextCursor:z65.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z66}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,PUBLICATION_NOTIFICATION_TOPICS,NOTIFICATION_TOPICS,NotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationWorkSessionSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z66.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z66.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z66.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z66.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z66.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("user"),userId:z66.string().min(1)}).strict(),z66.object({kind:z66.literal("agent"),agentKey:z66.string().min(1).max(120),agentId:z66.uuid().optional()}).strict(),z66.object({kind:z66.literal("system")}).strict()]),NotificationSummarySchema=z66.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z66.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z66.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z66.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z66.object({sessionId:z66.uuid(),branch:z66.string().min(1),targetBranch:z66.string().min(1),revision:z66.string().min(1),fingerprint:z66.string().min(1)}),NotificationPayloadSchema=z66.discriminatedUnion("topic",[z66.object({topic:z66.literal("agent_question"),questionId:z66.uuid(),title:z66.string().trim().min(1).max(80),description:z66.string().trim().min(1).max(240)}).strict(),z66.object({topic:z66.literal("agent_run_outcome"),threadId:z66.uuid(),invocationId:z66.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z66.object({topic:z66.literal("agent_retained_review"),threadId:z66.uuid().optional(),invocationId:z66.uuid().optional(),proposalId:z66.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z66.object({topic:z66.literal("agent_conflict"),mergeId:z66.uuid(),threadId:z66.uuid().optional(),invocationId:z66.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z66.object({topic:z66.literal("publication_failed"),publicationId:z66.uuid(),sourceBranch:z66.string().trim().min(1).max(120),failureCode:z66.string().trim().min(1).max(64),failedAt:z66.iso.datetime(),firstPublication:z66.boolean()}).strict()]),NotificationEnvelopeSchema=z66.object({id:z66.uuid(),projectId:z66.uuid(),sourceKey:z66.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z66.literal(1),payload:NotificationPayloadSchema,createdAt:z66.coerce.date()}),NotificationDeliveryStateSchema=z66.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z66.object({id:z66.uuid(),notificationRecipientId:z66.uuid(),projectId:z66.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z66.number().int().nonnegative(),nextAttemptAt:z66.coerce.date().nullable(),lastAttemptAt:z66.coerce.date().nullable(),sentAt:z66.coerce.date().nullable(),failureCode:z66.string().max(80).nullable(),createdAt:z66.coerce.date(),updatedAt:z66.coerce.date()}),NotificationPreferenceSchema=z66.object({topic:WorkNotificationTopicSchema,channel:z66.literal("email"),enabled:z66.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z66.enum(["default","explicit"])}),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z66.object({enabled:z66.boolean(),pausedUntil:z66.coerce.date().nullable(),source:z66.enum(["default","explicit"]).optional()})}});import{z as z67}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","publishing","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z67.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_question","work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance","usage.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z67.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z67.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z67.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z67.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z67.object({enabled:z67.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z67.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z67.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z67.discriminatedUnion("kind",[z67.object({kind:z67.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z67.enum(["work_review","publishing","schedule","usage"]),enabled:z67.boolean(),source:PreferenceSourceSchema}).strict(),z67.object({kind:z67.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z67.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z67.object({kind:z67.literal("pause_toggle"),id:z67.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z67.literal("question_digest"),enabled:z67.boolean(),source:PreferenceSourceSchema,pausedUntil:z67.coerce.date().nullable()}).strict(),z67.object({kind:z67.literal("provider_subscription"),id:z67.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z67.literal("marketing"),name:z67.string(),description:z67.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z67.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z67.object({email:EmailNotificationPreferenceSchema,entries:z67.array(NotificationPreferenceEntrySchema),unavailableGroups:z67.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z67.object({enabled:z67.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z67.discriminatedUnion("kind",[z67.object({kind:z67.literal("toggle"),enabled:z67.boolean()}).strict(),z67.object({kind:z67.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z67.object({kind:z67.literal("pause_toggle"),enabled:z67.boolean(),pauseDays:z67.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."),z67.object({kind:z67.literal("provider_subscription"),enabled:z67.boolean()}).strict()])}});import{z as z68}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=z68.object({surface:SurfaceNameSchema,key:z68.string(),label:z68.string()}),InlineSchema=z68.object({text:z68.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z68.discriminatedUnion("type",[z68.object({type:z68.literal("paragraph"),content:z68.array(InlineSchema).max(24)}),z68.object({type:z68.literal("preview"),ref:DiffRefSchema,caption:z68.string().optional()}),z68.object({type:z68.literal("code"),code:z68.string(),lang:z68.string().optional(),caption:z68.string().optional()}),z68.object({type:z68.literal("risk"),level:z68.enum(["warning","error"]),content:z68.array(InlineSchema).max(24)}),z68.object({type:z68.literal("list"),items:z68.array(z68.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z68.object({headline:z68.string(),blocks:z68.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z68.object({summary:EnvDiffSummarySchema,fingerprint:z68.string(),generatedAt:z68.coerce.date(),cached:z68.boolean().optional(),credits:z68.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z69}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,PROJECT_ANALYTICS_TRACKING_STATES,ProjectAnalyticsTrackingStatusDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsTrackingStatusDTO,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=z69.object({date:z69.string(),visitors:z69.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z69.object({key:z69.string(),visitors:z69.number().int().nonnegative(),pageviews:z69.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z69.object({path:z69.string(),pageName:z69.string().nullable().optional(),visitors:z69.number().int().nonnegative(),pageviews:z69.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z69.object({preset:z69.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z69.string(),requestedTo:z69.string(),effectiveFrom:z69.string(),effectiveTo:z69.string(),isRetentionLimited:z69.boolean(),groupBy:z69.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z69.object({date:z69.string(),content:z69.string(),updatedAt:z69.string(),updatedByUserId:z69.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z69.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z69.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z69.number().int().nonnegative(),pageviews:z69.number().int().nonnegative(),botPageviews:z69.number().int().nonnegative(),botVisitors:z69.number().int().nonnegative(),bounceRate:z69.number().min(0).max(100),viewsPerVisit:z69.number().nonnegative(),averageVisitDurationSeconds:z69.number().nonnegative(),visitorsSeries:z69.array(ProjectDailyVisitorsDTOSchema),topPages:z69.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z69.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z69.object({state:z69.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z69.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z70}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=z70.object({id:z70.string(),email:z70.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z70.coerce.date(),createdAt:z70.coerce.date(),inviterUserId:z70.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z70.object({id:z70.string(),token:z70.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z70.object({success:z70.boolean(),projectId:z70.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z71}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=z71.object({id:z71.string(),name:z71.string(),image:z71.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z71.object({count:z71.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z71.object({counts:z71.object({signed_up:z71.int(),activated:z71.int()}),credits:z71.object({total:z71.int(),earned:z71.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z71.email(),emailVerified:z71.boolean(),createdAt:z71.coerce.date(),updatedAt:z71.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z72}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=z72.object({id:z72.string(),principalType:ProjectPrincipalTypeSchema,principalId:z72.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z72.coerce.date(),expiresAt:z72.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","knowledge:view","knowledge:edit","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=z72.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z72.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z72.record(z72.string(),z72.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z72.object({access:z72.array(ProjectAccessItemDTOSchema),invites:z72.array(ProjectInviteDTOSchema),organization:z72.object({name:z72.string().nullable(),logo:z72.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z72.object({success:z72.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z72.object({success:z72.boolean(),projectId:z72.uuid()}))}});import{z as z73}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=z73.object({publicationStatus:PublicationStatusSchema,appUrl:z73.string().nullable(),lastPublishedAt:z73.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z74}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=z74.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z74.object({branch:BranchSchema,revision:z74.string().min(1).max(64).nullable(),generation:z74.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z74.url().nullable()})}});import{z as z75}from"zod";var PreviewUpgradeRequiredSchema,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();PreviewUpgradeRequiredSchema=z75.object({code:z75.literal("PREVIEW_UPGRADE_REQUIRED"),message:z75.string(),currentVersion:z75.number().int().positive(),targetVersion:z75.literal(4)}),PreviewBridgePackageSchema=z75.object({name:z75.string().min(1),version:z75.string().min(1)}),PreviewBridgeCapabilitySchema=z75.object({integrated:z75.boolean(),packages:z75.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z75.object({url:z75.url(),expiresAt:z75.iso.datetime().nullable(),source:z75.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z75.object({name:z75.string().min(1),locator:z75.string().min(1).optional(),source:z75.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z75.object({kind:z75.literal("dependency_build_scripts_blocked"),packageManager:z75.enum(["pnpm","yarn","bun"]),packages:z75.array(z75.string()),targets:z75.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z75.string(),approvalKey:z75.string(),command:z75.string().optional(),approval:z75.object({id:z75.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z75.object({code:z75.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z75.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z75.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z75.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z75.object({message:z75.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z75.number().int().optional().catch(void 0),logTail:z75.array(z75.string()).optional().catch(void 0),logTailTruncated:z75.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z75.object({approvalId:z75.uuid()}),PreviewInstallPolicyApprovalEventSchema=z75.discriminatedUnion("type",[z75.object({type:z75.literal("progress"),step:z75.enum(["approval","install","restart","readiness"]),message:z75.string()}),z75.object({type:z75.literal("approved")}),z75.object({type:z75.literal("complete")}),z75.object({type:z75.literal("error"),code:z75.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z75.string()})])}});import{z as z76}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:z76.string(),slug:z76.string().nullable(),logo:z76.string().nullable(),metadata:z76.record(z76.string(),z76.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z76.object({id:z76.string(),name:z76.string(),email:z76.email(),image:z76.string().nullable()}),OrganizationMemberDTOSchema=z76.object({id:z76.string(),userId:z76.string(),organizationId:z76.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z76.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z77}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,AgentRuntimeOverageRefusalSchema,AgentRuntimeOverageDTOSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,OptionalSpendRefusalSchema,CreditPurchasePricingDTOSchema,CreditPurchasePricingDTO,PurchaseCreditsDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,PaymentRecoveryInvoiceDTOSchema,PaymentRecoveryDTOSchema,PaymentRecoveryDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,CreditPurchasePricingResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,PaymentRecoveryResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common2();init_create_dto();init_response();CancellationReasonCodeSchema=z77.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z77.object({reason:CancellationReasonCodeSchema,details:z77.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z77.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z77.object({offerVersion:z77.string().trim().min(1),unusedPremiumCreditAmount:z77.number().int().nonnegative(),amountDueNow:z77.number().int().nonnegative(),renewsOn:z77.string()}),PlanMigrationPreviewDTOSchema=z77.object({currency:z77.string().trim().min(1),unusedPremiumCreditAmount:z77.number().int().nonnegative(),amountDueNow:z77.number().int().nonnegative(),startsAt:z77.string(),renewsAt:z77.string(),nextRenewalAmount:z77.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z77.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z77.object({id:z77.string(),organizationId:z77.string(),legacySubscriptionId:z77.string(),offeredPlanCode:z77.string(),offeredPlanName:z77.string(),offeredPriceAmount:z77.number(),offeredCurrency:z77.string(),offerVersion:z77.string(),state:PlanMigrationStateSchema,checkoutToken:z77.string().nullable(),deadlineAt:z77.string(),transitions:z77.array(z77.object({event:z77.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z77.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z77.object({included:z77.number().optional(),unitPrice:z77.number().optional(),dailyCap:z77.number().nullable().optional()}),EntitlementsDTOSchema=z77.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z77.object({retentionDays:z77.number().int().positive(),canUseExtendedDateRanges:z77.boolean()}).optional(),history:z77.object({retentionDays:z77.number().int().positive()}).optional(),members:z77.object({canInvite:z77.boolean(),maxMembers:z77.number().int().positive().nullable()}).optional(),projects:z77.object({maxProjects:z77.number().int().positive().nullable()}).optional(),domains:z77.object({canUseCustomDomains:z77.boolean(),maxDomains:z77.number().int().nonnegative().nullable()}).optional(),media_storage:z77.object({limitBytes:z77.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z77.object({usedBytes:z77.number().int().nonnegative().nullable(),limitBytes:z77.number().int().nonnegative().nullable(),state:z77.enum(["ready","unavailable"]),measuredAt:z77.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z77.object({toPlanCode:TemplateCodeSchema,effectiveAt:z77.string(),scheduledAt:z77.string().nullable()}),AutomaticSpendStopDTOSchema=z77.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z77.string(),spendStopped:z77.boolean(),settlementEndsAt:z77.string()}),HostingOverageStatusDTOSchema=z77.object({state:z77.enum(["ready","unavailable"]),planCode:z77.string(),overageAvailable:z77.boolean(),overageEnabled:z77.boolean(),monthlyCapUsd:z77.number().int().positive().nullable(),agentRuntimeEnabled:z77.boolean(),agentRuntimeAvailable:z77.boolean(),periodStart:z77.iso.datetime().nullable(),periodEnd:z77.iso.datetime().nullable(),usedBytes:z77.number().nonnegative().nullable(),includedBytes:z77.number().nonnegative().nullable(),overageBytes:z77.number().nonnegative(),currentOverageAmountMicros:z77.number().nonnegative().nullable(),agentRuntimeAmountMicros:z77.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z77.number().nonnegative().nullable(),currency:z77.string().nullable(),status:z77.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z77.object({enabled:z77.boolean(),monthlyCapUsd:z77.number().int().positive().max(1e6).optional(),agentRuntimeEnabled:z77.boolean().optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z77.object({id:z77.string(),external_id:z77.string(),customerId:z77.string(),planId:z77.string(),planCode:z77.union([TemplateCodeSchema,z77.literal("Unknown")]),currentPeriod:z77.object({start:z77.string(),end:z77.string().nullable()}),cancelAt:z77.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z77.string(),nextPaymentAt:z77.string().nullable(),baseAmount:z77.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z77.object({totalCap:z77.number(),dailyCap:z77.number(),usedTotal:z77.number()}),CreditBalanceDTOSchema=z77.object({total:z77.number(),base:z77.number(),dailyBase:z77.number(),purchases:z77.number(),awards:z77.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z77.object({total:z77.number(),nearLimit:z77.boolean(),canChat:z77.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z77.object({dailyFreeAvailable:z77.number(),monthlyAvailable:z77.number(),purchasedAvailable:z77.number(),awardedAvailable:z77.number()}),ProjectDailyCreditAllowanceDTOSchema=z77.object({periodCap:z77.number(),dailyGrant:z77.number(),usedThisPeriod:z77.number(),remainingThisPeriod:z77.number()}),ProjectCreditBalanceDTOSchema=z77.object({projectId:z77.uuid(),organizationId:z77.string(),balance:z77.object({totalAvailable:z77.number(),nearLimit:z77.boolean(),canUseAi:z77.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z77.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z77.enum(["ok","near_limit","exhausted"]),AgentRuntimeOverageRefusalSchema=z77.enum(["plan_unknown","plan_cannot_fund","pending_plan_exit","consent_missing"]),AgentRuntimeOverageDTOSchema=z77.object({available:z77.boolean(),enabled:z77.boolean(),status:z77.enum(["included","paid","paused"]),pauseReason:AgentRuntimeOverageRefusalSchema.nullable(),rateUsdPerHour:z77.number().nonnegative().nullable(),monthlyCapUsd:z77.number().positive().nullable(),consentedAt:z77.coerce.date().nullable(),billableMs:z77.number().int().nonnegative(),paidRemainingMs:z77.number().int().nonnegative(),projectedAmountUsd:z77.number().nonnegative().nullable()}),AgentRuntimeUsageDTOSchema=z77.object({planCode:z77.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z77.object({source:z77.enum(["cached_subscription","free_fallback"]),settledMs:z77.number().int().nonnegative(),activeMs:z77.number().int().nonnegative(),reservedMs:z77.number().int().nonnegative().optional(),includedMs:z77.number().int().positive(),remainingMs:z77.number().int().nonnegative(),extraMs:z77.number().int().nonnegative(),resetsAt:z77.coerce.date()}),overage:AgentRuntimeOverageDTOSchema}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z77.discriminatedUnion("enabled",[z77.object({enabled:z77.literal(!0),thresholdUsd:z77.number().nonnegative(),refillAmountUsd:z77.number().nonnegative()}),z77.object({enabled:z77.literal(!1),thresholdUsd:z77.number().nonnegative().nullable(),refillAmountUsd:z77.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z77.discriminatedUnion("enabled",[z77.object({enabled:z77.literal(!0),thresholdUsd:z77.number().min(.01).multipleOf(.01),refillAmountUsd:z77.number().min(.01).multipleOf(.01),expectedRateToken:z77.string().trim().min(1).max(40)}).strict(),z77.object({enabled:z77.literal(!1),thresholdUsd:z77.number().min(.01).multipleOf(.01),expectedRateToken:z77.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z77.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z77.object({planCode:z77.union([TemplateCodeSchema,z77.literal("Unknown")]).nullable(),canPurchase:z77.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z77.number().int().positive(),minAmountUsd:z77.number().positive(),maxAmountUsd:z77.number().positive(),rateToken:z77.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z77.object({amountUsd:z77.number(),idempotencyKey:z77.string().trim().min(8).max(120),expectedRateToken:z77.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z77.object({invoiceId:z77.string(),newBalance:z77.int(),creditCount:z77.int(),amountUsd:z77.number(),creditsPerDollar:z77.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z77.object({url:z77.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z77.object({id:z77.string(),number:z77.string().nullable(),status:z77.string(),amountDue:z77.int(),currency:z77.string(),issuedAt:z77.string().nullable(),hostedInvoiceUrl:z77.string().nullable()}),PaymentRecoveryDTOSchema=z77.discriminatedUnion("status",[z77.object({status:z77.literal("eligible"),checkedAt:z77.string()}),z77.object({status:z77.literal("recovery_required"),checkedAt:z77.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z77.int().min(1)}),z77.object({status:z77.literal("unavailable"),checkedAt:z77.string(),reason:z77.enum(["provider_error","truncated","unattempted","foreign_invoice","unknown_status"])})]),PaymentRecoveryDTO=createDTO(PaymentRecoveryDTOSchema),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),PaymentRecoveryResponseSchema=createResponseSchema2(PaymentRecoveryDTOSchema)}});import{z as z78}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=z78.object({brand:z78.string(),last4:z78.string(),exp:z78.string(),isDefault:z78.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z79}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=z79.string().superRefine((path53,ctx)=>{let segments=path53.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=z79.object({type:z79.literal("renameField"),contentType:z79.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z79.object({enabled:z79.boolean()}).strict(),ContentFieldGroupSchema=z79.object({id:z79.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z79.string().min(1).max(255),default:z79.boolean().optional()}).strict(),ContentTypeDTOSchema=z79.object({id:z79.string(),name:z79.string(),label:z79.string(),isSingleton:z79.boolean(),i18n:ContentTypeI18nSchema,groups:z79.array(ContentFieldGroupSchema).default([]),fields:z79.record(z79.string(),FieldDefinitionSchema),createdAt:z79.string(),updatedAt:z79.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z79.object({contentTypes:z79.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z79.object({id:z79.string(),entryId:z79.string(),documentId:z79.string(),slug:z79.string(),locale:z79.string().optional(),createdAt:z79.string(),updatedAt:z79.string(),__fimo:z79.object({contentType:z79.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({limit:z79.number(),offset:z79.number(),total:z79.number(),hasMore:z79.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z79.object({contentType:z79.string(),count:z79.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z79.object({counts:z79.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z79.object({count:z79.number().int().nonnegative(),sourceLocale:z79.string(),targetLocale:z79.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z79.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z79.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z79.union([z79.string(),z79.number(),z79.boolean(),z79.null()]),entryWhereOperatorSchema2=z79.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z79.array(entryWhereScalarSchema2).optional(),$nin:z79.array(entryWhereScalarSchema2).optional(),$contains:z79.string().optional(),$startsWith:z79.string().optional(),$null:z79.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z79.record(z79.string(),z79.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z79.record(z79.string(),z79.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z79.object({data:z79.record(z79.string(),z79.unknown()),locale:z79.string().min(1).optional(),documentId:z79.uuid().optional()}),entryIdsSchema=z79.array(z79.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z79.object({sql:z79.string().min(1)}),BulkCreateEntriesRequestSchema=z79.object({entries:z79.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z79.union([z79.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z79.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z79.object({updates:z79.array(z79.object({id:z79.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z79.union([z79.object({ids:entryIdsSchema,locale:z79.string().min(1).optional()}),z79.object({where:EntryWhereSchema2,locale:z79.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z79.object({data:z79.array(z79.record(z79.string(),z79.unknown())),meta:z79.object({rowCount:z79.number().int().nonnegative(),truncated:z79.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({created:z79.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({updated:z79.number().int().nonnegative(),missing:z79.array(z79.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({deleted:z79.number().int().nonnegative(),missing:z79.array(z79.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z80}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z80.object({index:z80.number().int().nonnegative(),contentType:z80.string(),field:z80.string(),value:z80.string(),against:z80.enum(["stored","batch"]),ownerDocumentId:z80.uuid().optional(),ownerIndex:z80.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z80.object({code:z80.literal("unique_conflict"),message:z80.string(),conflicts:z80.array(UniqueConflictSchema),truncated:z80.boolean().optional()})}});import{z as z81}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=z81.object({kind:z81.literal("unique_conflict"),contentType:z81.string(),field:z81.string(),value:z81.string(),documentCount:z81.number().int().positive(),documentIds:z81.array(z81.uuid()),documentIdsTruncated:z81.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z81.object({code:z81.literal("schema_transition_rejected"),message:z81.string(),issues:z81.array(SchemaTransitionIssueSchema),truncated:z81.boolean().optional()})}});import{z as z82}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=z82.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z82.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z82.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z82.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z82.object({field:CmsFieldNameSchema,direction:z82.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z82.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z82.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z82.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z82.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z82.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z83}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=z83.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z84}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=z84.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z84.object({event:ClientTrackedEventSchema,properties:z84.record(z84.string(),z84.unknown()).default({})})}});import{z as z85}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=z85.object({id:z85.string(),name:z85.string()}),AssetDTOSchema2=z85.object({id:z85.string(),name:z85.string(),type:AssetTypeSchema,originalFileName:z85.string().nullable(),parentId:z85.string().nullable(),mimeType:z85.string().nullable(),fileSize:z85.number().nullable(),url:z85.string().nullable(),storageKey:z85.string().nullable(),createdAt:z85.string(),updatedAt:z85.string(),altText:z85.string().nullable().optional(),caption:z85.string().nullable().optional(),aiCaption:z85.string().nullable().optional(),aiAltText:z85.string().nullable().optional(),aiTags:z85.array(z85.string()).nullable().optional(),aiPrimaryColor:z85.string().nullable().optional(),aiProcessingStatus:z85.string().nullable().optional(),width:z85.number().nullable().optional(),height:z85.number().nullable().optional(),path:z85.array(AssetPathItemSchema).optional(),hasChildren:z85.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z85.lazy(()=>z85.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z85.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z85.object({error:z85.string(),code:z85.literal("media_storage_limit_exceeded"),usedBytes:z85.number().int().nonnegative(),limitBytes:z85.number().int().positive(),incomingBytes:z85.number().int().nonnegative()}),AssetReferenceScopeSchema=z85.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z85.object({assetIds:z85.array(z85.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z85.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z85.object({totalFiles:z85.number().int().nonnegative(),checkedFiles:z85.number().int().nonnegative(),limit:z85.number().int().positive()}),AssetReferenceFindingDTOSchema=z85.object({assetId:z85.uuid(),entryId:z85.string(),documentId:z85.string(),contentType:z85.string(),locale:z85.string().nullable(),slug:z85.string(),fieldPath:z85.string()}),AssetReferenceScopeResultDTOSchema=z85.object({scope:AssetReferenceScopeSchema,label:z85.string(),state:z85.enum(["available","not-published","failed"]),coverage:z85.enum(["complete","partial","failed"]),referenceCount:z85.number().int().nonnegative().optional(),codeReferenceCount:z85.number().int().nonnegative().optional(),referencedAssetIds:z85.array(z85.uuid()).optional(),references:z85.array(AssetReferenceFindingDTOSchema),reason:z85.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z85.discriminatedUnion("type",[z85.object({type:z85.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z85.object({type:z85.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z85.object({type:z85.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z85.object({replacementAssetId:z85.uuid()}),AssetReferenceReplacementResultSchema=z85.object({referencesReplaced:z85.number().int().nonnegative(),entriesChanged:z85.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z85.object({referencesReplaced:z85.number().int().nonnegative(),filesChanged:z85.number().int().nonnegative(),commitSha:z85.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z85.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=z85.object({error:z85.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z85.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=z85.object({intent:AssetRemovalIntentSchema,assetIds:z85.array(z85.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z85.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=z85.object({id:z85.uuid(),intent:AssetRemovalIntentSchema,assetIds:z85.array(z85.uuid()),replacementAssetId:z85.uuid().nullable(),expiresAt:z85.iso.datetime(),undoable:z85.boolean(),requestedByMe:z85.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z85.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z85.object({error:z85.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z86}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z86.object({key:z86.string(),value:z86.string().optional(),defaultValue:z86.string(),locale:z86.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z87}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=z87.object({id:z87.string(),name:z87.string(),type:z87.enum(["file","folder"]),path:z87.string(),children:z87.lazy(()=>z87.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z87.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z87.object({path:z87.string(),exists:z87.boolean(),type:z87.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z88}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=z88.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z88.object({minLength:z88.number().optional(),maxLength:z88.number().optional(),min:z88.number().optional(),max:z88.number().optional(),pattern:z88.string().optional(),maxFileSize:z88.number().optional(),accept:z88.array(z88.string()).optional()}),FormFieldSchema=z88.object({type:FormFieldTypeSchema,label:z88.string(),placeholder:z88.string().optional(),required:z88.boolean().optional(),defaultValue:z88.string().optional(),options:z88.array(z88.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z88.record(z88.string(),FormFieldSchema),FormContentSchema2=z88.object({name:z88.string().min(1).max(255),label:z88.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 z89}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatDTOSchema,ProjectChatListDTOSchema,ProjectChatCreatedDTOSchema,ProjectChatTitleSchema,ProjectChatUpdateSchema,ProjectChatStateSchema,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_chat_portrait();init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z89.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z89.object({items:z89.array(ProjectMessagePublicDTOSchema),nextCursor:z89.string().nullable()}),ChatLiveTurnDTOSchema=z89.object({invocationId:z89.string(),step:z89.enum(["preparing","working","compacting","merging"]),startedAt:z89.string(),continuesInvocationId:z89.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z89.object({threadId:z89.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z89.object({id:z89.string(),role:z89.enum(["user","assistant"]),parts:z89.array(z89.unknown()),metadata:z89.record(z89.string(),z89.unknown()).nullable(),versionId:z89.string().nullable().optional(),createdAt:z89.date().transform(value=>value.toISOString()),providerMessageId:z89.string().nullable().optional(),source:z89.string().nullable().optional(),invocationId:z89.string().nullable().optional(),invocationStatus:z89.string().nullable().optional(),invocationTerminalReason:z89.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z89.object({id:z89.string(),parts:z89.array(z89.unknown()),metadata:z89.record(z89.string(),z89.unknown()).nullable(),providerMessageId:z89.string().nullable().optional(),source:z89.string().nullable().optional(),failed:z89.boolean(),queuedAt:z89.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z89.object({type:z89.literal("merge_conflict"),merge:z89.object({mergeId:z89.string().uuid(),projectId:z89.string(),fromBranch:z89.string(),toBranch:z89.string()}),publishAfterMerge:z89.boolean()}),ChatThreadMessagesPageDTOSchema=z89.object({threadId:z89.string().nullable(),title:z89.string().nullable(),messages:z89.array(ChatThreadMessageDTOSchema),nextCursor:z89.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z89.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z89.boolean().optional()}),ChatReplayOutcomeDTOSchema=z89.object({kind:z89.literal("replay"),threadId:z89.string(),userMessageId:z89.string()}),ChatQueuedOutcomeDTOSchema=z89.object({kind:z89.literal("queued"),threadId:z89.string(),userMessageId:z89.string(),blockingRootId:z89.string().optional()}),ChatBusyOutcomeDTOSchema=z89.object({kind:z89.literal("busy"),threadId:z89.string(),userMessageId:z89.string(),blockingRootId:z89.string().optional()}),ChatRefusedOutcomeDTOSchema=z89.object({kind:z89.literal("refused"),threadId:z89.string(),userMessageId:z89.string(),refusedInvocationId:z89.string(),terminalReason:z89.string()}),ChatNonStreamingOutcomeDTOSchema=z89.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatDTOSchema=z89.object({id:z89.string().uuid(),title:z89.string().nullable(),createdAt:z89.string(),lastMessageAt:z89.string().nullable(),preview:z89.string().nullable(),running:z89.boolean(),unread:z89.boolean(),pinned:z89.boolean(),archived:z89.boolean(),muted:z89.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z89.object({chats:z89.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z89.object({id:z89.string().uuid()}),ProjectChatTitleSchema=z89.string().trim().min(1).max(120),ProjectChatUpdateSchema=z89.object({title:ProjectChatTitleSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.portrait!==void 0,"Set a title or a portrait"),ProjectChatStateSchema=z89.object({read:z89.boolean(),pinned:z89.boolean(),archived:z89.boolean(),muted:z89.boolean()}).partial().refine(state=>Object.keys(state).length>0,"Set at least one of read, pinned, archived or muted"),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema)}});import{z as z90}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=z90.object({url:z90.string().url(),key:z90.string(),size:z90.number(),contentType:z90.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z91}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=z91.object({canAccess:z91.boolean(),permissions:z91.record(z91.string(),z91.boolean()),role:z91.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z92}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:z92.string().trim().default(""),sort:z92.enum(["recent","name","relevance"]).default("recent"),category:z92.string().optional()})}});import{z as z93}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=z93.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z93.enum(["fimo","external"]),PaymentStatusSchema=z93.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z93.object({id:z93.string().uuid(),domain:z93.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z93.boolean(),price:z93.number().int().nullable(),renewalPrice:z93.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z93.string().nullable(),failureReason:z93.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z93.object({domain:z93.string(),available:z93.boolean(),premium:z93.boolean(),price:z93.number().nullable(),renewalPrice:z93.number().nullable(),purchaseType:z93.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z93.object({domain:z93.string(),price:z93.number().nullable(),renewalPrice:z93.number().nullable(),premium:z93.boolean(),allowedYears:z93.array(z93.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z93.object({firstName:z93.string().max(100),lastName:z93.string().max(100),companyName:z93.string().max(100).optional(),address1:z93.string().max(255),address2:z93.string().max(255).optional(),city:z93.string().max(100),state:z93.string().max(100),zip:z93.string().max(20),country:z93.string().max(2),phone:z93.string().max(30),email:z93.union([z93.string().email().max(255),z93.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z93.object({firstName:z93.string().min(1).max(100),lastName:z93.string().min(1).max(100),companyName:z93.string().max(100).optional(),address1:z93.string().min(1).max(255),address2:z93.string().max(255).optional(),city:z93.string().min(1).max(100),state:z93.string().min(1).max(100),zip:z93.string().min(1).max(20),country:z93.string().min(1).max(2),phone:z93.string().min(1).max(30),email:z93.string().email().max(255)}),SearchDomainsRequestSchema=z93.object({keyword:z93.string().min(1).max(100),tldFilter:z93.array(z93.string()).optional()}),CheckAvailabilityRequestSchema=z93.object({domains:z93.array(z93.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=z93.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z93.object({domain:DomainNameSchema,years:z93.number().int().min(1).max(10).optional().default(3),autoRenew:z93.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z93.object({autoRenew:z93.boolean().optional()}),RenewDomainRequestSchema=z93.object({years:z93.number().int().min(1).max(10).optional().default(1),autoRenew:z93.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z93.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z93.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z93.object({verified:z93.boolean(),email:z93.string().nullable(),verifyBy:z93.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z94}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=z94.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=z94.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=z94.object({txtName:z94.string().nullable().optional(),txtValue:z94.string().nullable().optional(),httpUrl:z94.string().nullable().optional(),httpBody:z94.string().nullable().optional(),cname:z94.string().nullable().optional(),cnameTarget:z94.string().nullable().optional()}),SSLValidationErrorSchema=z94.object({message:z94.string()}),OwnershipVerificationSchema=z94.object({type:z94.string(),name:z94.string(),value:z94.string()}),ProjectDomainSSLDTOSchema=z94.object({status:z94.string(),method:z94.string().nullable(),type:z94.string().nullable(),validationRecords:z94.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z94.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z94.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z94.enum(["subdomain","apex"]),RedirectConfigSchema=z94.object({type:z94.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z94.string()}).nullable().optional(),ProjectDomainDTOSchema=z94.object({id:z94.string(),hostname:z94.string(),status:z94.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z94.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z94.string(),scdCnameTarget:z94.string().optional(),apexTargets:z94.array(z94.string()),dnsAutoConfigured:z94.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z94.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z94.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z94.object({hostname:z94.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:z94.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z94.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z94.object({available:z94.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z94.object({success:z94.boolean(),hostname:z94.string()}))}});import{z as z95}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=z95.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z95.object({available:z95.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z95.object({slug:z95.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z95.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z95.object({subdomain:z95.string(),subdomainUpdatedAt:z95.coerce.date()})),SubdomainSuggestionsQuerySchema=z95.object({base:z95.string().max(100).optional(),max:z95.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z95.object({suggestions:z95.array(z95.string())}))}});import{z as z96}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=z96.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z96.object({code:ProjectTransferBlockerCodeSchema,message:z96.string(),count:z96.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z96.object({targetOrganizationId:z96.string().min(1)}),ProjectTransferResultDTO=createDTO(z96.object({projectId:z96.string(),sourceOrganizationId:z96.string(),targetOrganizationId:z96.string(),movedThreads:z96.number().int().nonnegative(),revokedInvites:z96.number().int().nonnegative(),revokedGrants:z96.number().int().nonnegative(),preservedGrants:z96.number().int().nonnegative(),warnings:z96.array(z96.string())}))}});import{z as z97}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=z97.object({translated:z97.number().int().nonnegative(),total:z97.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z97.object({locale:z97.string(),isDefault:z97.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z97.object({defaultLocale:z97.string(),locales:z97.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z97.object({locale:z97.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z97.object({locale:z97.string().min(1).max(40)}),ProjectLocaleMutationSchema=z97.object({locale:z97.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z97.object({locale:z97.string(),entriesDeleted:z97.number().int().nonnegative(),labelsDeleted:z97.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z98}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=z98.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z98.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=z98.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z98.number(),credits:z98.number().optional(),billingMode:z98.enum(["fimo-credits","provider-account"]).optional(),confidence:z98.enum(["exact","estimated","metered"]),basis:z98.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z99}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=z99.object({options:z99.record(z99.string(),z99.unknown()),name:z99.string().optional(),parentId:z99.string().nullable().optional(),altText:z99.string().optional(),caption:z99.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z99.string().min(1).optional(),model:z99.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=z99.object({jobId:z99.string(),status:z99.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z99.string().nullable().optional(),credits:z99.number().optional(),costUsd:z99.number().optional(),billingMode:z99.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z99.object({error:z99.string(),code:z99.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:z99.array(GenerationTaskIdSchema).optional(),availableModels:z99.array(z99.string()).optional(),issues:z99.array(z99.unknown()).optional()})}});import{z as z100}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=z100.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z100.object({name:z100.string(),key:z100.string(),description:z100.string(),type:FlagTypeSchema,required:z100.boolean(),defaultValue:z100.unknown().optional(),enumValues:z100.array(z100.string()).optional(),isArray:z100.boolean()}),AssetModelPriceSchema=z100.object({unitPrice:z100.number(),unit:z100.string(),confidence:z100.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z100.object({id:z100.string(),shortName:z100.string(),provider:z100.string(),source:z100.string(),modality:z100.enum(["image","video","audio"]),tags:z100.array(z100.string()),displayName:z100.string(),description:z100.string(),flags:z100.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z100.object({model:z100.string(),costUsd:z100.number(),credits:z100.number(),billingMode:z100.enum(["fimo-credits","provider-account"]),confidence:z100.enum(["exact","estimated","metered"]),basis:z100.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z101}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=z101.object({tourId:z101.string(),version:z101.string(),status:z101.string(),completedAt:z101.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z101.array(UserTourDTOSchema))}});import{z as z102}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=z102.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z102.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z102.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z102.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z102.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z102.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z102.enum(["user","agent","system"]),SupportReportTagSchema=z102.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z102.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z102.object({organization:z102.object({id:z102.string().trim().min(1).max(255),name:z102.string().trim().max(240).optional()}),project:z102.object({id:z102.uuid(),name:z102.string().trim().max(240).optional(),createdAt:z102.coerce.date().optional()}).optional(),environment:z102.string().trim().max(255).optional(),clientVersion:z102.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z102.object({message:z102.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z102.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z102.string().trim().max(200).optional(),limit:z102.coerce.number().int().min(1).max(100).default(50),offset:z102.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z102.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z102.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z102.uuid().nullable().optional(),note:z102.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=z102.object({message:z102.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z102.object({kind:SupportReportLinkKindSchema,label:z102.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z102.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z102.object({kind:SupportReportActorKindSchema,id:z102.string().nullable(),name:z102.string().nullable()}),SupportReportLinkDTOSchema=z102.object({id:z102.uuid(),kind:SupportReportLinkKindSchema,label:z102.string(),url:SupportReportHttpUrlSchema,externalId:z102.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z102.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z102.object({id:z102.uuid(),kind:SupportReportEventKindSchema,body:z102.string().nullable(),metadata:z102.record(z102.string(),z102.unknown()),actor:SupportReportActorDTOSchema,createdAt:z102.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z102.object({id:z102.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z102.array(z102.string()),source:SupportReportSourceSchema,message:z102.string(),reporter:z102.object({id:z102.string().nullable(),name:z102.string().nullable(),email:z102.string().nullable()}),organization:z102.object({id:z102.string().nullable(),name:z102.string()}),project:z102.object({id:z102.uuid().nullable(),name:z102.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z102.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z102.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z102.string().nullable(),deliveredAt:z102.coerce.date().nullable()}).nullable(),duplicateOfReportId:z102.uuid().nullable(),resolvedAt:z102.coerce.date().nullable(),createdAt:z102.coerce.date(),updatedAt:z102.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z102.string().nullable(),clientVersion:z102.string().nullable(),links:z102.array(SupportReportLinkDTOSchema),events:z102.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z102.object({reports:z102.array(SupportReportSummaryDTOSchema),total:z102.number().int().nonnegative(),statusCounts:z102.object({new:z102.number().int().nonnegative(),in_progress:z102.number().int().nonnegative(),waiting:z102.number().int().nonnegative(),resolved:z102.number().int().nonnegative(),duplicate:z102.number().int().nonnegative(),irrelevant:z102.number().int().nonnegative(),ignored:z102.number().int().nonnegative()}),limit:z102.number().int().positive(),offset:z102.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z102.object({id:z102.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z102.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z103}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=z103.iso.datetime({offset:!0}).pipe(z103.coerce.date()),OpsRecentChatInputSchema=z103.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z103.string().trim().min(1).max(255).optional(),limit:z103.coerce.number().int().min(1).max(200).default(100),cursor:z103.string().trim().min(1).max(2e3).optional(),slim:z103.boolean().default(!0),reason:z103.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=z103.object({id:z103.string(),threadId:z103.string(),providerMessageId:z103.string().nullable(),invocationId:z103.string().nullable(),env:z103.string().nullable(),role:z103.string(),parts:z103.array(z103.record(z103.string(),z103.unknown())),metadata:z103.object({status:z103.string().optional(),traceUrl:z103.string().optional(),externalFileChanges:z103.array(z103.unknown()).optional()}),stats:z103.object({toolCount:z103.number().int().nonnegative(),failedToolCount:z103.number().int().nonnegative()}),createdAt:z103.iso.datetime({offset:!0}),project:z103.object({id:z103.string(),name:z103.string(),displayName:z103.string().nullable(),organizationId:z103.string().nullable()})}),OpsRecentChatResponseSchema=z103.object({target:z103.object({backendProfile:OpsBackendProfileSchema,projectEnv:z103.string().nullable()}),window:z103.object({from:z103.iso.datetime({offset:!0}),to:z103.iso.datetime({offset:!0})}),messages:z103.object({items:z103.array(OpsRecentChatMessageSchema),nextCursor:z103.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z104}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=z104.object({backendProfile:OpsBackendProfileSchema,provider:z104.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z104.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z104.object({backendProfile:OpsBackendProfileSchema,provider:z104.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z104.literal(!1),reason:z104.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z105}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=z105.object({packageManager:z105.string().trim().min(1).max(200).nullable(),trackedLockfiles:z105.array(z105.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z105.string().trim().min(1)}),OpsProjectPackageManagerSchema=z105.object({target:z105.object({backendProfile:OpsBackendProfileSchema,projectId:z105.uuid(),projectEnv:z105.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z106}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=z106.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=z106.object({branch:BranchSchema,sessionId:z106.uuid()}),OpsAgentBranchDiscardPlanInputSchema=z106.object({branches:OpsAgentBranchAllowlistSchema,reason:z106.string().trim().min(1).max(1e3),recoveredOwners:z106.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:z106.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=z106.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z107}from"zod";function createAgentRunWebhookEventDataSchema(status){return z107.object({run:z107.object({id:z107.string(),agentName:z107.string(),trigger:z107.string(),status:z107.literal(status),startedAt:z107.string().nullable(),finishedAt:z107.string().nullable(),reason:z107.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=z107.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z107.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z107.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z107.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z107.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z107.object({reason:WebhookEntryChangeReasonSchema,operationId:z107.string().optional(),batch:z107.object({index:z107.number().int().positive(),total:z107.number().int().positive()}).optional(),changes:z107.array(z107.object({action:WebhookEntryChangeActionSchema,contentType:z107.string(),id:z107.string(),documentId:z107.string(),locale:z107.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z107.object({form:z107.object({id:z107.string(),label:z107.string()}),submission:z107.object({id:z107.string(),data:z107.record(z107.string(),z107.unknown()),submittedAt:z107.string()})}),PublishStartedWebhookEventDataSchema=z107.object({publication:z107.object({status:z107.literal("publishing"),startedAt:z107.string()})}),PublishSucceededWebhookEventDataSchema=z107.object({publication:z107.object({status:z107.literal("published"),url:z107.string(),publishedAt:z107.string(),firstPublish:z107.boolean()})}),PublishFailedWebhookEventDataSchema=z107.object({publication:z107.object({status:z107.literal("failed"),reason:z107.string()})}),PublishUnpublishedWebhookEventDataSchema=z107.object({publication:z107.object({previousUrl:z107.string(),unpublishedAt:z107.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z107.object({review:z107.object({runId:z107.string(),agentName:z107.string(),reason:z107.string()}),source:z107.object({branch:z107.string(),revision:z107.string(),anchorBranch:z107.string()})}),AgentReviewResolvedWebhookEventDataSchema=z107.object({review:z107.object({id:z107.string(),runId:z107.string(),agentName:z107.string(),resolution:z107.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z107.object({report:z107.object({weekStart:z107.string(),weekEnd:z107.string(),pageviews:z107.number(),visitors:z107.number(),previousPageviews:z107.number(),previousVisitors:z107.number()})}),MediaAssetWebhookEventDataSchema=z107.object({id:z107.string().nullable(),name:z107.string().nullable(),type:z107.string(),mimeType:z107.string().nullable(),fileSize:z107.number().nullable()}),MediaUploadedWebhookEventDataSchema=z107.object({asset:MediaAssetWebhookEventDataSchema,operation:z107.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z107.object({asset:MediaAssetWebhookEventDataSchema,operation:z107.literal("updated")}),MediaDeletedWebhookEventDataSchema=z107.object({asset:MediaAssetWebhookEventDataSchema,operation:z107.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z107.object({domain:z107.object({id:z107.string(),hostname:z107.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z107.object({domain:z107.object({id:z107.string(),hostname:z107.string()})}),LabelChangedWebhookEventDataSchema=z107.object({changes:z107.array(z107.object({action:z107.enum(["created","updated","deleted"]),key:z107.string(),locale:z107.string(),value:z107.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z107.object({locale:z107.object({code:z107.string(),isDefault:z107.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z107.object({locale:z107.object({code:z107.string(),previousCode:z107.string()})}),LocaleDeletedWebhookEventDataSchema=z107.object({locale:z107.object({code:z107.string(),entriesDeleted:z107.number().int().nonnegative(),labelsDeleted:z107.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z107.object({environment:z107.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z107.object({environment:z107.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z107.object({merge:z107.object({id:z107.string(),from:BranchSchema,to:BranchSchema,applied:z107.array(z107.object({surface:SurfaceNameSchema,count:z107.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z107.object({branch:z107.object({name:BranchSchema}),version:z107.object({versionId:z107.uuid(),name:z107.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=z107.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z107.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z107.discriminatedUnion("source",[z107.object({source:z107.literal("literal"),value:z107.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z107.object({source:z107.literal("secret"),key:z107.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z107.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z107.object({name:z107.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z107.object({name:z107.string(),source:z107.enum(["literal","secret"]),secretKey:z107.string().nullable(),secretPrefix:z107.string().nullable(),configured:z107.literal(!0)}),WebhookFilterSchema=z107.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z107.string().min(1).max(255).optional(),agentName:z107.string().min(1).max(120).optional(),mediaType:z107.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z107.string().min(1).max(255).optional(),locale:z107.string().min(1).max(120).optional()}),JsonValueSchema=z107.lazy(()=>z107.union([z107.string(),z107.number(),z107.boolean(),z107.null(),z107.array(JsonValueSchema),z107.record(z107.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z107.object({name:z107.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z107.url(),enabled:z107.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z107.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z107.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z107.object({name:z107.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z107.url().optional(),enabled:z107.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z107.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z107.boolean().optional()}),TestProjectWebhookRequestSchema=z107.object({eventType:WebhookEventTypeSchema.optional(),data:z107.record(z107.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z107.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z107.uuid(),name:z107.string(),eventType:WebhookEventTypeSchema,enabled:z107.boolean(),destination:z107.object({host:z107.string(),maskedUrl:z107.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z107.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z107.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z107.coerce.date().nullable(),deliveryStats24h:z107.object({succeeded:z107.number().int().nonnegative(),failed:z107.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z107.uuid(),projectId:z107.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z107.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z107.number().int().positive(),test:z107.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z107.number().int().nonnegative(),responseStatus:z107.number().int().nullable(),lastErrorCode:z107.string().nullable(),lastErrorMessage:z107.string().nullable(),payloadAvailable:z107.boolean(),destination:z107.object({host:z107.string(),maskedUrl:z107.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z107.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z107.string().nullable(),qstashMessageId:z107.string().nullable(),deliveredAt:z107.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z107.object({items:z107.array(WebhookDeliveryDTOSchema),pagination:z107.object({page:z107.number().int().positive(),limit:z107.number().int().positive(),total:z107.number().int().nonnegative(),totalPages:z107.number().int().positive(),hasMore:z107.boolean()}),stats:z107.object({total:z107.number().int().nonnegative(),succeeded:z107.number().int().nonnegative(),failed:z107.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z107.object({id:z107.uuid(),deliveryId:z107.uuid(),attempt:z107.number().int().positive(),status:z107.enum(["delivering","succeeded","failed"]),responseStatus:z107.number().int().nullable(),durationMs:z107.number().int().nonnegative(),responseExcerpt:z107.string().nullable(),errorCode:z107.string().nullable(),errorMessage:z107.string().nullable(),createdAt:z107.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z107.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z107.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z108}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=z108.object({key:z108.literal("fimo-2"),enabled:z108.boolean(),dismissed:z108.boolean().default(!1),interacted:z108.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z109}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=z109.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z109.object({total:z109.number(),base:z109.number(),purchases:z109.number(),awards:z109.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z109.object({id:z109.string(),name:z109.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z109.object({type:z109.string(),brand:z109.string().nullable(),last4:z109.string().nullable(),expirationDate:z109.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z109.object({currency:z109.string(),nextPaymentAmount:z109.number().nullable(),nextPaymentAt:z109.string().nullable(),billingInterval:z109.string().nullable(),totalAmount:z109.number().nullable(),discountAmount:z109.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z109.object({id:z109.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z109.string().nullable(),currentPeriodEndsAt:z109.string().nullable(),renewsAt:z109.string().nullable(),cancelAt:z109.string().nullable(),renewAutomatically:z109.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z109.object({type:z109.enum(["low_balance","critical_balance","approaching_limit"]),message:z109.string(),estimatedPromptsRemaining:z109.number().nullable(),avgCostPerPrompt:z109.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z109.object({monthlyCredits:z109.number().nullable(),usedThisPeriod:z109.number(),remainingThisPeriod:z109.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z109.object({organizationId:z109.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z109.string().nullable(),tenureDays:z109.number().int().nonnegative(),capturedAt:z109.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z109.object({hasSubscription:z109.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z109.number().nullable(),alerts:z109.array(CreditAlertDTOSchema),portalUrl:z109.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z109.object({creditCount:z109.number().int().positive(),expiresAt:z109.string().datetime().nullable().optional(),message:z109.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z109.literal("free"),amountCents:z109.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z109.literal("purchase"),amountCents:z109.number().int().positive()}),CreditTopupRequestDTOSchema=z109.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z109.object({success:z109.boolean(),transactionId:z109.string().nullable(),newBalance:z109.number(),creditCount:z109.number(),type:z109.enum(["free","purchase"]),invoiceId:z109.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z110}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=z110.object({totalCredits:z110.number(),totalCostUsd:z110.number(),totalMessages:z110.number(),avgCostPerMessage:z110.number(),periodStart:z110.string().nullable(),periodEnd:z110.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z110.object({projectId:z110.string(),projectName:z110.string(),projectDisplayName:z110.string().nullable(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z110.object({userId:z110.string(),userName:z110.string().nullable(),userEmail:z110.string().email().nullable(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z110.object({date:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z110.object({userId:z110.string(),userName:z110.string().nullable(),userEmail:z110.string().email().nullable(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z110.object({projectId:z110.string(),projectName:z110.string(),projectDisplayName:z110.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z110.array(UsageByUserForProjectDTOSchema),timeline:z110.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z110.object({summary:UsageSummaryDTOSchema,byProject:z110.array(UsageByProjectDTOSchema),byUser:z110.array(UsageByUserDTOSchema),timeline:z110.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z111}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=z111.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z111.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z111.object({startDate:z111.string().optional(),endDate:z111.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z111.coerce.number().int().positive().default(1),limit:z111.coerce.number().int().positive().max(100).default(20),sortBy:z111.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z111.string().optional(),activeOnly:z111.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z111.object({totalCredits:z111.number(),totalCostUsd:z111.number(),totalMessages:z111.number(),avgCostPerMessage:z111.number(),avgCreditsPerMessage:z111.number(),periodStart:z111.string(),periodEnd:z111.string(),creditsChange:z111.number().nullable(),costChange:z111.number().nullable(),messagesChange:z111.number().nullable(),unattributedCredits:z111.number(),unattributedCostUsd:z111.number(),unattributedMessages:z111.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z111.object({date:z111.string(),credits:z111.number(),costUsd:z111.number(),messages:z111.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z111.object({organizationId:z111.string(),organizationName:z111.string(),credits:z111.number(),costUsd:z111.number(),messages:z111.number(),percentage:z111.number(),userCount:z111.number(),projectCount:z111.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z111.object({userId:z111.string(),userName:z111.string().nullable(),userEmail:z111.string().nullable(),userImage:z111.string().nullable(),organizationId:z111.string().nullable(),organizationName:z111.string().nullable(),credits:z111.number(),costUsd:z111.number(),messages:z111.number(),percentage:z111.number(),projectCount:z111.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z111.object({projectId:z111.string(),projectName:z111.string(),projectDisplayName:z111.string().nullable(),organizationId:z111.string(),organizationName:z111.string(),credits:z111.number(),costUsd:z111.number(),messages:z111.number(),percentage:z111.number(),userCount:z111.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z111.object({id:z111.string(),name:z111.string(),value:z111.number(),percentage:z111.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z111.object({day:z111.number(),hour:z111.number(),value:z111.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z111.object({summary:UsageOverviewSummaryDTOSchema,timeline:z111.array(UsageTimelinePointDTOSchema),topOrganizations:z111.array(OrganizationUsageRowDTOSchema),topUsers:z111.array(UserUsageRowDTOSchema),topProjects:z111.array(ProjectUsageRowDTOSchema),creditDistribution:z111.array(UsageDistributionItemDTOSchema),userDistribution:z111.array(UsageDistributionItemDTOSchema),heatmap:z111.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z111.object({page:z111.number(),limit:z111.number(),totalItems:z111.number(),totalPages:z111.number(),hasMore:z111.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z111.object({organizations:z111.array(OrganizationUsageRowDTOSchema),top:z111.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z111.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z111.object({users:z111.array(ExtendedUserUsageRowDTOSchema),top:z111.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z111.string(),ownerName:z111.string().nullable(),ownerEmail:z111.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z111.object({projects:z111.array(ExtendedProjectUsageRowDTOSchema),top:z111.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z111.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z111.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z111.object({credits:z111.number(),costUsd:z111.number(),messages:z111.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z111.object({id:z111.string(),name:z111.string(),createdAt:z111.string(),memberCount:z111.number(),projectCount:z111.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z111.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z111.object({id:z111.string(),name:z111.string().nullable(),email:z111.string(),image:z111.string().nullable(),createdAt:z111.string(),organizationCount:z111.number(),projectCount:z111.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z111.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z111.object({id:z111.string(),name:z111.string(),displayName:z111.string().nullable(),createdAt:z111.string(),organizationId:z111.string(),organizationName:z111.string(),ownerId:z111.string(),ownerName:z111.string().nullable(),ownerEmail:z111.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z111.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z112}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=z112.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z112.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z112.object({command:z112.string().min(1).max(1e4),cwd:z112.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z112.record(z112.string(),z112.string()).optional(),name:z112.string().optional(),waitForCompletion:z112.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=z112.object({identifier:z112.string(),status:SandboxProcessStatusSchema,command:z112.string().optional(),startedAt:z112.string().optional(),exitCode:z112.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z112.object({processes:z112.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z112.object({processId:z112.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z112.object({success:z112.boolean(),message:z112.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z113}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z113.enum(["internal","user-visible"]),SessionSetRetentionSchema=z113.object({additionalDays:z113.number().int().min(1).max(30)}).strict()}});import{z as z114}from"zod";var PROJECT_KNOWLEDGE_MAX_CHARACTERS,ProjectKnowledgeContentSchema,ProjectKnowledgeDTOSchema,ProjectKnowledgeUpdateSchema,ProjectKnowledgeResponseSchema,ProjectKnowledgeDraftDTOSchema,ProjectKnowledgeDraftResponseSchema,ProjectKnowledgeDraftStartSchema,init_project_knowledge_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-knowledge.dto.js"(){"use strict";init_response();PROJECT_KNOWLEDGE_MAX_CHARACTERS=1e4,ProjectKnowledgeContentSchema=z114.string().refine(value=>[...value].length<=PROJECT_KNOWLEDGE_MAX_CHARACTERS&&new TextEncoder().encode(value).length<=4e4,"Knowledge must contain at most 10,000 characters and 40 KB of UTF-8 text"),ProjectKnowledgeDTOSchema=z114.object({content:ProjectKnowledgeContentSchema,updatedAt:z114.string().nullable(),updatedBy:z114.string().nullable()}),ProjectKnowledgeUpdateSchema=z114.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema2(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z114.object({id:z114.uuid(),status:z114.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z114.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema2(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z114.object({idempotencyKey:z114.uuid()})}});import{z as z115}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_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_chat_portrait();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();init_work_sessions();init_project_knowledge_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(`
198
+ `)}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=z47.enum(REPORT_TONES),blockCommon={title:z47.string().trim().min(1).max(120).optional(),fallback:z47.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z47.object({type:z47.literal("text"),...blockCommon,text:z47.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=z47.object({type:z47.literal("metric"),...blockCommon,items:z47.array(z47.object({value:z47.string().trim().min(1).max(24),unit:z47.string().trim().min(1).max(12).optional(),label:z47.string().trim().min(1).max(160),note:z47.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z47.array(z47.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=z47.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z47.object({type:z47.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z47.string().trim().min(1).max(12).optional(),points:z47.array(z47.object({label:z47.string().trim().min(1).max(24),value:z47.number().finite(),highlight:z47.boolean().optional()}).strict()).min(2).max(24),caption:z47.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=z47.object({type:z47.literal("list"),...blockCommon,items:z47.array(z47.object({tone:ReportToneSchema.optional(),label:z47.string().trim().min(1).max(24).optional(),heading:z47.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z47.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z47.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=z47.object({type:z47.literal("table"),...blockCommon,columns:z47.array(z47.object({label:z47.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z47.array(z47.object({cells:z47.array(z47.object({text:z47.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z47.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=z47.object({type:z47.literal("media"),...blockCommon,assetId:z47.uuid(),alt:z47.string().trim().min(1).max(300),caption:z47.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=z47.object({type:z47.literal("links"),...blockCommon,items:z47.array(z47.object({label:z47.string().trim().min(1).max(120),url:z47.url({protocol:/^https$/}).max(2e3),description:z47.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z47.object({type:z47.literal("code"),...blockCommon,language:z47.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z47.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z47.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z47.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z47.object({title:z47.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z47.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z47.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=z47.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=z47.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z47.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 z48}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=z48.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z48.object({dev:z48.string().trim().min(1).optional(),build:z48.string().trim().min(1).optional(),install:z48.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z48.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z48.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z48.object({type:z48.enum(["header","cookie","query","host"]),key:z48.string().min(1).optional(),value:z48.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:z48.array(FimoHostingConditionSchema).min(1).optional(),missing:z48.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z48.object({source:z48.string().min(1),destination:z48.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z48.object({source:z48.string().min(1),destination:z48.string().min(1),permanent:z48.boolean().optional(),statusCode:z48.union([z48.literal(301),z48.literal(302),z48.literal(307),z48.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z48.object({source:z48.string().min(1),headers:z48.array(z48.object({key:z48.string().min(1),value:z48.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z48.object({rewrites:z48.array(FimoHostingRewriteSchema).optional(),redirects:z48.array(FimoHostingRedirectSchema).optional(),headers:z48.array(FimoHostingHeaderSchema).optional(),cleanUrls:z48.boolean().optional(),trailingSlash:z48.boolean().optional()}).strict(),FimoAppConfigSchema=z48.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 isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path53){return[...path53.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path53,params){return pageRouteParamNames(path53).filter(param=>!LOCALE_PARAM_NAME.test(param)&&params?.[param]?.type!=="external")}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";__name(isEntryParamBinding,"isEntryParamBinding");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 z49}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,PublishUpgradeRequiredSchema,ProjectLatestPublicationAttemptSchema,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.5","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","openai/gpt-6.1-sol","openai/gpt-6-sol","openai/gpt-6-luna","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=z49.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z49.string(),displayName:z49.string().nullable(),subdomain:z49.string().nullable().optional(),subdomainUpdatedAt:z49.date().nullable().optional(),organizationId:z49.string().nullable(),createdBy:z49.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z49.boolean().default(!0),enabledChatModels:z49.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z49.string(),thumbnailUrl:z49.string().nullable(),publishedThumbnailUrl:z49.string().nullable(),category:z49.string().nullable(),snapshotUrl:z49.string().startsWith("/").optional(),appUrl:z49.string().nullable(),lastPublishedAt:z49.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z49.object({name:z49.string().optional(),previewEnabled:z49.boolean().optional(),enabledChatModels:z49.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z49.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z49.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z49.object({id:z49.uuid(),name:z49.string(),displayName:z49.string().nullable(),thumbnailUrl:z49.string().nullable(),category:z49.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z49.object({id:z49.string(),name:z49.string(),avatar:z49.string().nullable(),color:z49.object({bg:z49.string(),text:z49.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z49.object({path:z49.string(),content:z49.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z49.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z49.object({id:z49.string(),messageId:z49.string(),versionId:z49.string().nullable(),role:ProjectChatMessageRole,parts:z49.array(z49.any()),createdAt:z49.coerce.date()}),MessageUserMetadataSchema=z49.object({id:z49.string(),name:z49.string().nullable().optional(),image:z49.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z49.number(),metadata:z49.object({user:MessageUserMetadataSchema,changeManifest:z49.array(z49.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z49.object({versionId:z49.uuid(),commitHash:z49.string(),name:z49.string(),description:z49.string().nullable(),kind:z49.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z49.object({versionCount:z49.number().int().nonnegative(),snapshotBytes:z49.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z49.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z49.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z49.object({content:z49.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z49.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z49.object({success:z49.boolean(),message:z49.string().optional(),warning:z49.string().optional(),durationMs:z49.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z49.object({code:z49.literal("PUBLISH_UPGRADE_REQUIRED"),message:z49.string(),currentVersion:z49.number().int().positive(),targetVersion:z49.literal(4)}),ProjectLatestPublicationAttemptSchema=z49.object({publicationId:z49.uuid(),status:z49.enum(["queued","building","published","failed","canceled"]),failureCode:z49.string().nullable(),sourceBranch:z49.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z49.object({isPublished:z49.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z49.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z49.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z49.object({label:z49.string().trim().min(1).max(120).optional(),notes:z49.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z49.object({success:z49.boolean(),message:z49.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z49.boolean(),publicationId:z49.string().optional(),url:z49.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z50}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=z50.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z50.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z50.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z50.string().nullable(),deletedAt:z50.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z50.object({id:z50.union([z50.literal(PREVIEW_ENVIRONMENT_KEY),z50.uuid()]),name:z50.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z50.object({sessionId:z50.uuid(),name:z50.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z50.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=z50.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z50.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z50.object({surface:z50.enum(["code","schemas","content","translations","assets","forms"]),status:z50.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z50.number().int().nonnegative(),conflictCount:z50.number().int().nonnegative()}),BranchDiffResultSchema=z50.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z50.coerce.date(),surfaces:z50.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z51}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=z51.object({projectId:z51.uuid(),name:z51.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z51.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z51.literal("production"),sourceBranch:BranchSchema,isPublished:z51.boolean(),url:z51.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z51.literal(PREVIEW_ENVIRONMENT_KEY),kind:z51.literal("preview"),matchedBranchCount:z51.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z51.literal("custom"),matchedBranchCount:z51.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z51.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z51.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z51.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z51.object({deletedId:z51.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z52}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=z52.object({kind:z52.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z52.object({kind:z52.enum(["variable","secret"]),value:z52.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z52.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z52.object({kind:z52.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z52.object({id:z52.uuid(),projectId:z52.uuid(),key:z52.string(),kind:z52.literal("secret"),exposure:z52.literal("private"),environment:EnvironmentKeySchema,maskedValue:z52.string().optional(),createdAt:z52.date().transform(value=>value.toISOString()),updatedAt:z52.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z52.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z53}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=z53.object({success:z53.literal(!0),downloadUrl:z53.string(),expiresAt:z53.string(),fileSize:z53.number(),duration:z53.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z53.object({success:z53.literal(!0),projectId:z53.string(),projectName:z53.string(),displayName:z53.string(),projectUrl:z53.string(),duration:z53.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z53.object({contentTypes:z53.number(),entries:z53.number(),assets:z53.number(),translations:z53.number(),forms:z53.number(),codeFiles:z53.number(),assetFiles:z53.number()}),ImportPreviewSurfaceDTOSchema=z53.object({name:z53.string(),included:z53.boolean(),count:z53.number().optional(),note:z53.string().optional()}),ImportPreviewDTOSchema=z53.object({projectName:z53.string(),displayName:z53.string().nullable(),category:z53.string().nullable(),exportedAt:z53.string(),version:z53.string(),envScope:z53.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z53.array(ImportPreviewSurfaceDTOSchema),fileSize:z53.number(),fileName:z53.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z53.object({success:z53.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z54}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=z54.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z54.object({type:z54.literal("manual")}),ScheduleTriggerSchema=z54.object({type:z54.literal("schedule"),cron:z54.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:z54.string().optional()}),WebhookTriggerSchema2=z54.object({type:z54.literal("webhook"),path:z54.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z54.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z55}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=z55.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z55.object({token:z55.string().min(1),risk:CapabilityRiskTierSchema,description:z55.string()}),AgentSubAgentSummarySchema=z55.object({name:z55.string().min(1),grant:z55.enum(["inherit","explicit"]),effectiveCaps:z55.array(z55.string().min(1))}),AgentInstallSummaryDTOSchema=z55.object({agentName:z55.string().min(1),env:z55.string().min(1),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z55.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z55.array(CapabilitySummaryEntrySchema),criticalCapabilities:z55.array(CapabilitySummaryEntrySchema),subAgents:z55.array(AgentSubAgentSummarySchema),declaresDelegate:z55.boolean(),cycle:z55.array(z55.string()).nullable(),missingSubAgents:z55.array(z55.string()),warnings:z55.array(z55.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z56}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemAvailabilitySchema,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=z56.object({kind:TriggerKindSchema,summary:z56.string()}),AgentListItemTriggerStateSchema=z56.object({triggerIndex:z56.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z56.boolean(),wired:z56.boolean(),syncError:z56.string().nullable()}),AgentListItemAvailabilitySchema=z56.enum(["available","pending_merge"]),AgentListItemDTOSchema=z56.object({name:z56.string().min(1),description:z56.string().nullable(),goalFirstLine:z56.string().nullable(),declaredCapabilities:z56.array(CapabilitySummaryEntrySchema),triggers:z56.array(AgentListItemTriggerSchema),triggerStates:z56.array(AgentListItemTriggerStateSchema),availability:AgentListItemAvailabilitySchema,paused:z56.boolean(),nextRunAt:z56.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z56.array(AgentListItemDTOSchema))}});import{z as z57}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,AgentDeleteResultSchema,AgentDeleteResultDTO,AgentDeleteResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z57.object({paused:z57.boolean(),cancelledRuns:z57.number().int().nonnegative(),stopIncomplete:z57.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema),AgentDeleteResultSchema=z57.object({name:z57.string(),removedFiles:z57.number().int().positive(),commitSha:z57.string().nullable(),cancelledRuns:z57.number().int().nonnegative()}),AgentDeleteResultDTO=createDTO(AgentDeleteResultSchema),AgentDeleteResultResponseSchema=createResponseSchema2(AgentDeleteResultSchema)}});import{z as z58}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=z58.object({args:z58.unknown().optional(),requestId:z58.string().min(1).max(128).optional()}),DispatchSkippedSchema=z58.object({skipped:z58.enum(["no-manual-trigger","agent-not-deployed","agent-config-invalid","manual-trigger-not-synced","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])}),DispatchAcceptedSchema=z58.object({sessionId:z58.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z58.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z59}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=z59.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z59.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z59.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z59.object({verb:SurfaceDeltaVerbSchema,key:z59.string(),detail:z59.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z59.record(z59.string(),z59.unknown()).optional()}),PerSurfaceDeltaSchema=z59.object({surface:SurfaceNameSchema,status:z59.enum(["ok","timed_out","failed","unchanged"]),durationMs:z59.number().int().nonnegative().optional(),changedCount:z59.number().int().nonnegative(),conflictCount:z59.number().int().nonnegative(),items:z59.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z59.boolean().optional(),error:z59.string().optional()}),CrossSurfaceFindingSchema=z59.object({id:z59.string(),kind:z59.string(),description:z59.string(),severity:z59.enum(["warning","error"]),source:z59.object({surface:SurfaceNameSchema,key:z59.string()}),target:z59.object({surface:SurfaceNameSchema,key:z59.string()}),actions:z59.array(z59.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z59.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z59.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z59.coerce.date(),surfaces:z59.array(PerSurfaceDeltaSchema),agents:z59.array(z59.object({id:z59.string(),name:z59.string(),status:z59.enum(["active","paused","failed"]),lastRunAt:z59.coerce.date().nullable()})).optional(),crossSurface:z59.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z59.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z59.coerce.date(),surfaces:z59.array(PerSurfaceDeltaSchema),crossSurface:z59.array(CrossSurfaceFindingSchema).optional(),fingerprint:z59.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z59.object({path:z59.string(),state:z59.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z59.string(),additions:z59.number().int().nonnegative(),deletions:z59.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z59.object({oid:z59.string().optional(),content:z59.string().optional(),truncated:z59.boolean(),binary:z59.boolean()}),CodeConflictDetailSchema=z59.object({path:z59.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z59.string(),targetTipSha:z59.string(),mergeBaseSha:z59.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z59.object({id:z59.string(),slug:z59.string(),contentType:z59.string(),data:z59.record(z59.string(),z59.unknown()),updatedAt:z59.coerce.date()}),ContentRowDiffSchema=z59.object({collection:z59.string(),rowId:z59.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z59.object({name:z59.string(),label:z59.string(),isSingleton:z59.boolean(),fields:z59.record(z59.string(),z59.unknown())}),SchemaTypeDiffSchema=z59.object({typeName:z59.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z59.object({id:z59.string(),name:z59.string(),type:z59.enum(["file","folder"]),mimeType:z59.string().nullable(),storageKey:z59.string().nullable(),url:z59.string().nullable(),fileSize:z59.number().nullable(),width:z59.number().nullable(),height:z59.number().nullable(),altText:z59.string().nullable(),caption:z59.string().nullable(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AssetDiffSchema=z59.object({assetId:z59.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z59.object({locale:z59.string(),key:z59.string(),parent:z59.string().nullable(),child:z59.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z59.object({formName:z59.string(),label:z59.string().nullable(),schemaFingerprint:z59.string(),fields:z59.record(z59.string(),z59.unknown()),settings:z59.record(z59.string(),z59.unknown()).optional()}),FormSchemaDiffSchema=z59.object({formName:z59.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=z59.enum(CONFLICT_KINDS),ConflictSchema=z59.object({surface:SurfaceNameSchema,key:z59.string(),kind:ConflictKindSchema.optional(),description:z59.string(),parentValue:z59.unknown().optional(),childValue:z59.unknown().optional(),conflictingFields:z59.array(z59.string()).optional(),code:z59.object({path:z59.string(),unresolvable:z59.boolean().optional(),reason:z59.string().optional()}).optional()}),FieldPickSchema=z59.object({field:z59.string(),choice:z59.enum(["parent","child","pick","ai-pick"]),pickedValue:z59.unknown().optional(),aiSessionId:z59.string().optional()}),ConflictResolutionSchema=z59.object({surface:SurfaceNameSchema,key:z59.string(),choice:z59.enum(["parent","child","pick"]),pickedValue:z59.unknown().optional(),fieldPicks:z59.array(FieldPickSchema).optional()}),MergeResultSchema=z59.object({ok:z59.boolean(),mergeId:z59.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z59.array(z59.object({surface:SurfaceNameSchema,count:z59.number().int().nonnegative()})),conflicts:z59.array(ConflictSchema).optional(),summary:z59.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z59.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z59.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z59.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z59.boolean().optional()}),ResolvedStrategySchema=z59.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z59.boolean()}),MergeRequestSchema=z59.object({from:BranchSchema,allowDirectMerge:z59.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z59.object({mergeId:z59.string().uuid(),streamUrl:z59.string(),strategy:ResolvedStrategySchema,acceptedAt:z59.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z59.object({mergeId:z59.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z59.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z59.array(ConflictSchema),draftResolutions:z59.array(ConflictResolutionSchema),lastEditedBy:z59.string().nullable(),lastEditedAt:z59.coerce.date().nullable(),initiator:z59.object({userId:z59.string().nullable(),role:z59.string().nullable(),agentName:z59.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z59.object({resolutions:z59.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z59.object({mergeId:z59.string().uuid(),draftResolutions:z59.array(ConflictResolutionSchema),lastEditedAt:z59.coerce.date(),lastEditedBy:z59.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z59.object({mergeId:z59.string().uuid(),resolutions:z59.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z59.object({mergeId:z59.string().uuid()}),PublishReleaseRequestSchema=z59.object({version:z59.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z59.string().max(2e4).optional()}),PublishReleaseResultSchema=z59.object({releaseTag:z59.string(),sha:z59.string(),publishedAt:z59.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z60}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentRuntimeRefusalKindSchema,AgentRunStopContextSchema,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=z60.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z60.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z60.strictObject({branch:BranchSchema.optional(),project_agents_only:z60.coerce.boolean().optional(),agent_name:z60.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z60.coerce.date().optional(),page:z60.coerce.number().int().positive().default(1),limit:z60.coerce.number().int().positive().max(200).default(25),cursor:z60.coerce.date().optional()}),SessionMetricsSchema=z60.object({cpuMs:z60.number().nonnegative().default(0),netBytes:z60.number().nonnegative().default(0),walltimeMs:z60.number().nonnegative().default(0),llmTokensIn:z60.number().nonnegative().optional(),llmTokensOut:z60.number().nonnegative().optional(),stepCount:z60.number().int().nonnegative().optional(),toolCallCounts:z60.record(z60.string().min(1).max(120),z60.number().int().nonnegative()).optional(),toolCallOutcomes:z60.array(z60.object({toolName:z60.string().min(1).max(120),success:z60.boolean(),code:z60.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z60.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z60.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z60.object({capturedAt:z60.coerce.date(),fingerprint:z60.string().min(1).max(256),counts:z60.object({code:z60.number().int().nonnegative(),content:z60.number().int().nonnegative(),schemas:z60.number().int().nonnegative(),labels:z60.number().int().nonnegative(),assets:z60.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z60.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z60.object({diff:DiffReportSchema,code:z60.array(CodeFileDiffSchema.extend({raw:z60.string().max(24576)})).max(200),schemas:z60.array(SchemaTypeDiffSchema).max(200),content:z60.array(z60.object({key:z60.string().min(1).max(512),collection:z60.string().min(1).max(256),slug:z60.string().max(512).optional(),verb:z60.enum(["added","modified","deleted"]),fields:z60.array(z60.object({name:z60.string().min(1).max(256),before:z60.unknown().optional(),after:z60.unknown().optional()})).max(20)})).max(200),labels:z60.array(z60.object({key:z60.string().min(1).max(512),locale:z60.string().min(1).max(64).optional(),before:z60.unknown().nullable(),after:z60.unknown().nullable()})).max(200),assets:z60.array(z60.object({key:z60.string().min(1).max(512),name:z60.string().min(1).max(512),verb:z60.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentRuntimeRefusalKindSchema=z60.enum(["plan_cannot_fund","consent_missing","budget_spent"]),AgentRunStopContextSchema=z60.object({kind:z60.literal("agent_runtime_allowance"),refusal:AgentRuntimeRefusalKindSchema,planCode:z60.string(),includedMs:z60.number().int().nonnegative(),resetsAt:z60.coerce.date(),rateUsdPerHour:z60.number().nullable()}),AgentSessionDTOSchema=z60.strictObject({id:z60.uuid(),projectId:z60.uuid(),branch:BranchSchema,agentName:z60.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z60.unknown().optional(),capabilities:z60.array(z60.string()).optional(),dataSources:z60.array(z60.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z60.string().nullable(),startedAt:z60.coerce.date().nullable(),finishedAt:z60.coerce.date().nullable(),cancelledAt:z60.coerce.date().nullable(),costUsd:z60.number().nonnegative(),costCeilingUsd:z60.number().nonnegative(),creditsUsed:z60.number().int().nonnegative().nullable(),limitCredits:z60.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),lastCheckpointId:z60.uuid().nullable(),agentBranchId:z60.uuid().nullable(),parentSessionId:z60.uuid().nullable(),terminalReason:z60.string().nullable(),errorMessage:z60.string().nullable(),stopContext:AgentRunStopContextSchema.nullable().catch(null),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z60.string().nullable(),retainedBranch:BranchSchema.nullable().optional(),createdAt:z60.coerce.date(),updatedAt:z60.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z60.object({id:z60.uuid(),sessionId:z60.uuid(),checkpointIdx:z60.number().int().nonnegative(),payloadRef:z60.string(),payloadSizeBytes:z60.number().int().nonnegative(),checksum:z60.string().length(64),createdAt:z60.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z60.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z60.object({session:AgentSessionDTOSchema,checkpoints:z60.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z60.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=z60.object({reason:z60.string().min(1).max(120).optional()})}});import{z as z61}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,WorkSessionReviewSchema,RequestWorkSessionReviewSchema,WorkSessionReviewResultSchema,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();init_env_status_dto();AgentBranchClassificationSchema=z61.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z61.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z61.object({sessionId:z61.uuid(),branch:z61.string().min(1),targetBranch:z61.string().min(1),revision:z61.string().min(1),fingerprint:z61.string().min(1),source:z61.enum(["studio","slack","autonomous","mcp"]),threadId:z61.uuid().nullable(),invocationId:z61.uuid().nullable(),conversationBranch:z61.string().nullable(),capturedAt:z61.string(),surfaces:z61.array(PerSurfaceDeltaSchema).optional(),counts:z61.record(z61.string(),z61.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z61.strictObject({sessionId:z61.uuid(),summary:z61.string().trim().min(1).max(240),targetBranch:z61.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z61.object({requested:z61.literal(!0),alreadyRequested:z61.boolean(),reviewId:z61.uuid(),reviewUrl:z61.url(),status:z61.literal("pending"),sessionId:z61.uuid(),branch:z61.string(),targetBranch:z61.string(),revision:z61.string(),savedRevision:z61.string(),fingerprint:z61.string(),visibility:z61.literal("user-visible"),retention:z61.literal("durable"),expiresAt:z61.null(),merged:z61.literal(!1),published:z61.literal(!1),links:z61.object({preview:z61.url(),changes:z61.url(),conversation:z61.url().nullable()})}),AgentBranchProposalDTOSchema=z61.object({id:z61.uuid(),envId:z61.uuid(),sessionId:z61.uuid().nullable(),skillName:z61.string().min(1),classification:AgentBranchClassificationSchema,rationale:z61.string().nullable(),summary:z61.string().nullable(),surfaceDeltas:z61.record(z61.string(),z61.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z61.coerce.date(),decidedAt:z61.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z61.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z61.object({path:z61.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z61.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z61.object({code:z61.literal("merge_conflict"),message:z61.string(),conflicts:z61.record(z61.string(),z61.number().int().nonnegative())})}});import{z as z62}from"zod";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=z62.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z62.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=z62.object({description:z62.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z62.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z62.array(z62.uuid()).optional()}),AgentQuestionSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),threadId:z62.uuid(),invocationId:z62.uuid(),agentKey:z62.string().min(1).max(120),anchorEnv:z62.string().min(1).max(64),retainedEnv:z62.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z62.string().min(1).nullable(),continuationInvocationId:z62.uuid().nullable(),askedAt:z62.coerce.date(),expiresAt:z62.coerce.date(),closedAt:z62.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z62.object({questionId:z62.uuid(),invocationId:z62.uuid(),askedAt:z62.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z62.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z62.object({question:AgentQuestionSchema,continuationInvocationId:z62.uuid(),deduped:z62.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z63}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=z63.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z63.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z63.enum(["secret_text"]),IntegrationCredentialUsageSchema=z63.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z63.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z63.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z63.object({mode:IntegrationAuthModeSchema,label:z63.string().min(1),description:z63.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z63.object({id:z63.string().min(1),label:z63.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z63.boolean()}),IntegrationToolDefinitionDTOSchema=z63.object({key:z63.string().min(1),name:z63.string().min(1),description:z63.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z63.object({title:z63.string().min(1),description:z63.string().min(1),command:z63.string().min(1).optional()}),IntegrationInfoDTOSchema=z63.object({key:z63.string().min(1),name:z63.string().min(1),summary:z63.string().min(1),type:z63.enum(["native","mcp"]).optional(),url:z63.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z63.array(IntegrationAuthModeDTOSchema),credentials:z63.array(IntegrationCredentialDefinitionDTOSchema),tools:z63.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z63.enum(["available","unavailable"]).optional(),connectionCapabilities:z63.object({customIdentityCreation:z63.boolean()}).optional(),recipes:z63.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z63.object({projectId:z63.uuid(),integrationKey:z63.string().min(1),name:z63.string().min(1),summary:z63.string().min(1),installed:z63.boolean(),enabled:z63.boolean(),setupState:z63.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z63.string().nullable(),connectionId:z63.uuid().nullable().optional(),connectionAlias:z63.string().min(1).nullable().optional(),connectionStatus:z63.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z63.array(z63.string()),installedAt:z63.coerce.date().nullable(),updatedAt:z63.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z63.object({id:z63.uuid(),projectId:z63.uuid(),integrationKey:z63.string().min(1),enabled:z63.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z63.string(),connectionId:z63.uuid().nullable().optional(),connectionAlias:z63.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z63.array(z63.string()),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z63.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z63.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z63.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z63.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z63.object({id:z63.uuid(),organizationId:z63.string().min(1),integrationKey:z63.string().min(1),registrationId:z63.uuid().nullable(),alias:z63.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z63.string().min(1),externalAccountName:z63.string().nullable(),externalBotUserId:z63.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z63.array(z63.string()),connectedAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z63.boolean(),isDefault:z63.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z63.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z63.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z63.record(McpHeaderNameSchema,z63.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z63.object({alias:z63.string().min(1).max(120).optional(),token:z63.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z63.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=z63.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z63.object({displayName:z63.string().trim().min(1).max(35),backgroundColor:z63.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z63.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z63.discriminatedUnion("mode",[z63.object({mode:z63.literal("personal"),alias:z63.string().min(1).max(120),token:z63.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z63.boolean().optional()}),z63.object({mode:z63.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z63.boolean().optional(),registrationId:z63.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=z63.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z63.union([z63.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z63.object({type:z63.literal("mcp"),name:z63.string().trim().min(1).max(120),url:z63.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z63.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z63.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=z63.object({integrationKey:z63.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z63.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z63.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z63.literal("oauth"),connectUrl:z63.string().url(),expiresAt:z63.coerce.date()})]),ReusableMcpServerAuthKindSchema=z63.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z63.object({id:z63.uuid(),name:z63.string().min(1),host:z63.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z63.string().min(1),availability:z63.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z63.object({query:z63.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z63.object({serverId:z63.uuid()}),LinearOAuthApplicationDistributionSchema=z63.enum(["private","public"]),OrganizationLinearAppDTOSchema=z63.object({id:z63.uuid(),displayName:z63.string().min(1),description:z63.string().nullable(),iconUrl:z63.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z63.enum(["active","revoked"]),connectionIds:z63.array(z63.uuid()),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z63.object({appName:z63.string().trim().min(2).max(80),description:z63.string().trim().max(1e3).optional(),iconUrl:z63.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z63.object({projectId:z63.uuid(),registrationId:z63.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z63.object({integrationKey:z63.string().min(1),connectUrl:z63.string().url(),expiresAt:z63.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z63.discriminatedUnion("mode",[z63.object({mode:z63.literal("personal"),integrationKey:z63.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z63.object({mode:z63.literal("oauth"),integrationKey:z63.string().min(1),connectUrl:z63.string().url(),expiresAt:z63.coerce.date()})]),BindProjectChannelRequestSchema=z63.object({ref:z63.string().min(1),connectionAlias:z63.string().min(1).optional(),agentName:z63.string().min(1).max(160).nullable().optional(),force:z63.boolean().optional()}),ListProjectChannelsQuerySchema=z63.object({integrationKey:z63.string().min(1)}),SearchProjectChannelsQuerySchema=z63.object({integrationKey:z63.string().min(1),connectionAlias:z63.string().min(1),query:z63.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z63.object({id:z63.uuid(),projectId:z63.uuid(),integrationKey:z63.string().min(1),connectionId:z63.uuid(),externalWorkspaceId:z63.string().min(1),externalChannelId:z63.string().min(1),externalChannelName:z63.string().nullable(),agentName:z63.string().nullable(),enabled:z63.boolean(),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z63.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z63.object({id:z63.string().min(1),name:z63.string().min(1),visibility:z63.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z63.string().min(1).nullable(),canMove:z63.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z63.object({markdown:z63.boolean().optional(),summary:z63.boolean().optional(),links:z63.boolean().optional(),branding:z63.boolean().optional(),images:z63.boolean().optional(),html:z63.union([z63.literal("cleaned"),z63.literal("raw"),z63.boolean()]).optional(),json:z63.union([z63.boolean(),z63.object({prompt:z63.string().min(1).max(1e4),schema:z63.record(z63.string(),z63.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z63.object({url:z63.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional(),waitForMs:z63.number().int().min(0).max(3e4).optional(),maxAgeMs:z63.number().int().min(0).optional(),minAgeMs:z63.number().int().min(0).optional(),storeInCache:z63.boolean().optional(),proxy:z63.enum(["basic","enhanced","auto"]).optional(),mobile:z63.boolean().optional(),location:z63.object({country:z63.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z63.array(z63.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z63.object({query:z63.string().min(1),maxResults:z63.number().int().positive().max(20).optional(),sources:z63.array(z63.enum(["web","news","images"])).min(1).max(3).optional(),categories:z63.array(z63.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z63.enum(["hour","day","week","month","year"]).optional(),location:z63.string().min(1).max(160).optional(),country:z63.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z63.object({query:z63.string().min(1).max(500),maxResults:z63.number().int().min(1).max(100).optional(),types:z63.array(z63.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z63.array(z63.string().min(1).max(512)).min(1).max(20).optional(),sources:z63.array(z63.string().min(1).max(512)).min(1).max(20).optional(),passages:z63.number().int().min(1).max(5).optional(),skills:z63.literal("only").optional(),language:z63.string().min(1).optional(),topic:z63.string().min(1).optional(),license:z63.string().min(1).optional(),minStars:z63.number().int().min(0).optional(),maxStars:z63.number().int().min(0).optional(),archived:z63.boolean().optional(),fork:z63.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z63.object({query:z63.string().min(1).max(500),maxResults:z63.number().int().min(1).max(500).optional(),authors:z63.array(z63.string().min(1)).min(1).optional(),categories:z63.array(z63.string().min(1)).min(1).optional(),from:z63.iso.date().optional(),to:z63.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z63.object({paperId:z63.string().min(1).max(512),query:z63.string().min(1).max(500).optional(),maxPassages:z63.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z63.object({paperId:z63.string().min(1).max(512),intent:z63.string().min(1).max(500),mode:z63.enum(["similar","citers","references"]).optional(),maxResults:z63.number().int().min(1).max(500).optional(),rerank:z63.boolean().optional(),anchors:z63.array(z63.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z63.object({url:z63.string().url(),search:z63.string().min(1).optional(),limit:z63.number().int().positive().max(200).optional(),includeSubdomains:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z63.object({url:z63.string().url(),limit:z63.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z63.object({text:z63.string().min(1).max(200).optional(),cron:z63.string().min(1).max(120).optional(),timezone:z63.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z63.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z63.boolean().optional(),timeoutMs:z63.number().int().positive().max(12e4).optional(),waitForMs:z63.number().int().min(0).max(3e4).optional(),maxAgeMs:z63.number().int().min(0).optional(),minAgeMs:z63.number().int().min(0).optional(),storeInCache:z63.boolean().optional(),proxy:z63.enum(["basic","enhanced","auto"]).optional(),mobile:z63.boolean().optional(),location:z63.object({country:z63.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z63.array(z63.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z63.union([z63.object({type:z63.enum(["scrape","crawl"]).default("scrape"),urls:z63.array(z63.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z63.object({type:z63.literal("search"),queries:z63.array(z63.string().min(1).max(256)).min(1).max(12),searchWindow:z63.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z63.number().int().min(1).max(50).optional(),includeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z63.array(z63.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z63.object({name:z63.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z63.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z63.string().min(1).max(2e3).optional(),judgeEnabled:z63.boolean().optional(),retentionDays:z63.number().int().min(1).max(365).optional(),notification:z63.object({email:z63.object({enabled:z63.boolean().default(!0),recipients:z63.array(z63.string().email()).min(1).max(20),includeDiffs:z63.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=z63.object({monitorId:z63.string().uuid(),name:z63.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z63.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z63.string().min(1).max(2e3).optional(),judgeEnabled:z63.boolean().optional(),retentionDays:z63.number().int().min(1).max(365).optional(),status:z63.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z63.object({monitorId:z63.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z63.string().uuid()}),RunProjectIntegrationToolRequestSchema=z63.object({tool:z63.string().min(1),input:z63.record(z63.string(),z63.unknown()),connectionAlias:z63.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z63.object({provider:z63.string().min(1),providerCredits:z63.number().nonnegative().optional(),providerCostUsd:z63.number().nonnegative().optional(),requests:z63.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z63.object({credits:z63.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z63.object({url:z63.string(),provider:z63.literal("firecrawl"),title:z63.string().optional(),statusCode:z63.number().optional(),markdown:z63.string().optional(),summary:z63.string().optional(),links:z63.array(z63.string()).optional(),images:z63.array(z63.string()).optional(),html:z63.string().optional(),json:z63.unknown().optional(),branding:z63.record(z63.string(),z63.unknown()).optional(),warning:z63.string().optional()}),FirecrawlSearchToolOutputSchema=z63.object({query:z63.string(),provider:z63.literal("firecrawl"),warning:z63.string().optional(),results:z63.array(z63.object({title:z63.string(),url:z63.string(),snippet:z63.string().optional(),content:z63.string().optional(),score:z63.number().optional(),publishedAt:z63.string().optional()}))}),FirecrawlResearchPaperSchema=z63.object({paperId:z63.string(),primaryId:z63.string().optional(),ids:z63.record(z63.string(),z63.array(z63.string())).optional(),title:z63.string().optional(),abstract:z63.string().optional(),score:z63.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z63.object({text:z63.string(),score:z63.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),results:z63.array(z63.object({id:z63.string(),type:z63.string().min(1).optional(),url:z63.string(),title:z63.string().optional(),passages:z63.array(z63.object({text:z63.string()}).passthrough())}).passthrough()),coverage:z63.record(z63.string(),z63.string()).optional(),reranked:z63.boolean().optional(),repos:z63.array(z63.record(z63.string(),z63.unknown())).optional(),sources:z63.array(z63.record(z63.string(),z63.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),results:z63.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),paper:z63.record(z63.string(),z63.unknown()),paperId:z63.string().optional(),query:z63.string().optional(),passages:z63.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),results:z63.array(FirecrawlResearchPaperSchema),poolSize:z63.number().int().nonnegative(),truncated:z63.boolean(),note:z63.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z63.object({url:z63.string(),provider:z63.literal("firecrawl"),count:z63.number(),links:z63.array(z63.object({url:z63.string(),title:z63.string().optional(),description:z63.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z63.object({url:z63.string(),provider:z63.literal("firecrawl"),total:z63.number(),pages:z63.array(z63.object({url:z63.string(),title:z63.string().optional(),statusCode:z63.number().optional(),markdown:z63.string().optional(),summary:z63.string().optional(),links:z63.array(z63.string()).optional(),images:z63.array(z63.string()).optional(),html:z63.string().optional(),warning:z63.string().optional()})),warning:z63.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z63.object({cron:z63.string().optional(),text:z63.string().optional(),timezone:z63.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z63.object({id:z63.string().optional(),type:z63.enum(["scrape","crawl","search"]).optional(),urls:z63.array(z63.string()).optional(),queries:z63.array(z63.string()).optional(),searchWindow:z63.string().optional(),maxResults:z63.number().optional(),includeDomains:z63.array(z63.string()).optional(),excludeDomains:z63.array(z63.string()).optional(),scrapeOptions:z63.record(z63.string(),z63.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z63.object({id:z63.string(),name:z63.string(),status:z63.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z63.string().nullable().optional(),lastRunAt:z63.string().nullable().optional(),currentCheckId:z63.string().nullable().optional(),targets:z63.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z63.string().nullable().optional(),judgeEnabled:z63.boolean().optional(),estimatedCreditsPerMonth:z63.number().optional(),createdAt:z63.string().optional(),updatedAt:z63.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z63.object({id:z63.string(),monitorId:z63.string(),scheduledFor:z63.string().nullable().optional(),startedAt:z63.string().nullable().optional(),finishedAt:z63.string().nullable().optional(),estimatedCredits:z63.number().nullable().optional(),reservedCredits:z63.number().nullable().optional(),actualCredits:z63.number().nullable().optional(),billingStatus:z63.string().nullable().optional(),summary:z63.object({totalPages:z63.number().optional(),same:z63.number().optional(),changed:z63.number().optional(),new:z63.number().optional(),removed:z63.number().optional(),error:z63.number().optional()}).passthrough().optional(),error:z63.string().nullable().optional(),createdAt:z63.string().optional(),updatedAt:z63.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitors:z63.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitorId:z63.string(),deleted:z63.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitorId:z63.string(),checks:z63.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z63.object({provider:z63.literal("firecrawl"),monitorId:z63.string(),check:FirecrawlMonitorCheckOutputSchema,next:z63.string().optional()}),FirecrawlToolKeySchema=z63.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=z63.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z63.object({projectId:z63.uuid(),integrationKey:z63.string().min(1),tool:z63.string().min(1),connectionAlias:z63.string().min(1).nullable().optional(),output:z63.record(z63.string(),z63.unknown()),executedAt:z63.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z63.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z63.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z63.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z63.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z63.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z63.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z63.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z63.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z63.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z63.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z63.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z63.array(ProjectChannelCandidateDTOSchema))}});import{z as z64}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=z64.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z64.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z64.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z64.object({userId:z64.string().min(1),name:z64.string(),email:z64.string().min(1),subscribed:z64.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z64.object({maxSubscribers:z64.number().int().positive(),subscriberCount:z64.number().int().nonnegative(),effectiveRecipientCount:z64.number().int().nonnegative(),currentUserSubscribed:z64.boolean(),candidates:z64.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z64.object({userIds:z64.array(z64.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z64.object({topic:UserManagedNotificationTopicSchema,enabled:z64.boolean(),source:z64.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z64.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z64.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z64.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z64.string().nullable(),maskedEmail:z64.string().min(1),applied:z64.boolean(),expiresAt:z64.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z64.object({scheduleId:z64.string().min(1),scheduleName:z64.string(),projectId:z64.string().min(1),projectName:z64.string(),env:z64.string().min(1)}),FollowedSchedulesSchema=z64.object({schedules:z64.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z65}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=z65.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=z65.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z65.uuid(),env:z65.string().min(1),name:z65.string().min(1),cron:z65.string().min(1),command:z65.string().min(1),secretKeys:z65.array(z65.string().min(1)),enabled:z65.boolean(),lastRunAt:z65.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z65.string().nullable(),suspendedAt:z65.coerce.date().nullable().optional(),suspensionReason:z65.string().nullable().optional(),overPolicyReasons:z65.array(z65.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z65.object({name:z65.string().min(1).max(120),cron:z65.string().min(1).max(120),command:z65.string().min(1).max(500),secretKeys:z65.array(ProjectSecretKeySchema).default([]),enabled:z65.boolean().optional()}),UpdateProjectScheduleRequestSchema=z65.object({name:z65.string().min(1).max(120).optional(),cron:z65.string().min(1).max(120).optional(),command:z65.string().min(1).max(500).optional(),secretKeys:z65.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z65.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z65.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z65.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z65.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z65.object({maxRuns:z65.number().int().positive(),retentionDays:z65.number().int().positive().nullable(),outputRetentionDays:z65.number().int().positive(),maxOutputBytes:z65.number().int().positive()}),SchedulePolicyStateSchema=z65.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z65.object({code:z65.enum(["Free","PAYG","Premium","Pro"]),source:z65.enum(["cached_subscription","free_fallback"]),activeSchedules:z65.object({used:z65.number().int().nonnegative(),limit:z65.number().int().nonnegative()}),minCadenceMinutes:z65.number().int().positive(),maxRunMs:z65.number().int().positive(),concurrency:z65.object({used:z65.number().int().nonnegative(),limit:z65.number().int().positive()}),compute:z65.object({settledMs:z65.number().int().nonnegative(),activeMs:z65.number().int().nonnegative(),reservedMs:z65.number().int().nonnegative().optional(),includedMs:z65.number().int().nonnegative(),remainingMs:z65.number().int().nonnegative(),resetsAt:z65.coerce.date()}),upgrade:z65.object({code:z65.literal("Pro"),activeSchedulesLimit:z65.number().int().positive(),minCadenceMinutes:z65.number().int().positive(),maxRunMs:z65.number().int().positive(),maxConcurrentRuns:z65.number().int().positive(),computeIncludedMs:z65.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z65.array(z65.string())}),ProjectScheduleUsageSchema=z65.object({runCount:z65.number().int().nonnegative(),runsWithOutput:z65.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z65.object({id:z65.uuid(),scheduleId:z65.uuid(),projectId:z65.uuid(),env:z65.string().min(1),scheduleName:z65.string().min(1),command:z65.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z65.object({id:z65.string().min(1),name:z65.string().min(1)}).nullable(),queuedAt:z65.coerce.date(),startedAt:z65.coerce.date().nullable(),finishedAt:z65.coerce.date().nullable(),exitCode:z65.number().int().nullable(),errorCode:z65.string().nullable(),error:z65.string().nullable(),outputBytes:z65.number().int().nonnegative(),outputTruncated:z65.boolean(),outputExpiresAt:z65.coerce.date().nullable(),metadataExpiresAt:z65.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z65.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z65.coerce.date().nullable(),items:z65.array(z65.object({key:z65.string().min(1),updatedAt:z65.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z65.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z65.object({trigger:z65.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z65.object({limit:z65.coerce.number().int().min(1).max(100).default(25),cursor:z65.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z65.object({items:z65.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z65.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z65.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z65.object({items:z65.array(ProjectScheduleRunDTOSchema),nextCursor:z65.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z66}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,PUBLICATION_NOTIFICATION_TOPICS,NOTIFICATION_TOPICS,NotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationWorkSessionSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z66.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z66.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z66.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z66.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z66.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("user"),userId:z66.string().min(1)}).strict(),z66.object({kind:z66.literal("agent"),agentKey:z66.string().min(1).max(120),agentId:z66.uuid().optional()}).strict(),z66.object({kind:z66.literal("system")}).strict()]),NotificationSummarySchema=z66.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z66.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z66.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z66.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z66.object({sessionId:z66.uuid(),branch:z66.string().min(1),targetBranch:z66.string().min(1),revision:z66.string().min(1),fingerprint:z66.string().min(1)}),NotificationPayloadSchema=z66.discriminatedUnion("topic",[z66.object({topic:z66.literal("agent_question"),questionId:z66.uuid(),title:z66.string().trim().min(1).max(80),description:z66.string().trim().min(1).max(240)}).strict(),z66.object({topic:z66.literal("agent_run_outcome"),threadId:z66.uuid(),invocationId:z66.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z66.object({topic:z66.literal("agent_retained_review"),threadId:z66.uuid().optional(),invocationId:z66.uuid().optional(),proposalId:z66.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z66.object({topic:z66.literal("agent_conflict"),mergeId:z66.uuid(),threadId:z66.uuid().optional(),invocationId:z66.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z66.object({topic:z66.literal("publication_failed"),publicationId:z66.uuid(),sourceBranch:z66.string().trim().min(1).max(120),failureCode:z66.string().trim().min(1).max(64),failedAt:z66.iso.datetime(),firstPublication:z66.boolean()}).strict()]),NotificationEnvelopeSchema=z66.object({id:z66.uuid(),projectId:z66.uuid(),sourceKey:z66.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z66.literal(1),payload:NotificationPayloadSchema,createdAt:z66.coerce.date()}),NotificationDeliveryStateSchema=z66.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z66.object({id:z66.uuid(),notificationRecipientId:z66.uuid(),projectId:z66.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z66.number().int().nonnegative(),nextAttemptAt:z66.coerce.date().nullable(),lastAttemptAt:z66.coerce.date().nullable(),sentAt:z66.coerce.date().nullable(),failureCode:z66.string().max(80).nullable(),createdAt:z66.coerce.date(),updatedAt:z66.coerce.date()}),NotificationPreferenceSchema=z66.object({topic:WorkNotificationTopicSchema,channel:z66.literal("email"),enabled:z66.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z66.enum(["default","explicit"])}),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z66.object({enabled:z66.boolean(),pausedUntil:z66.coerce.date().nullable(),source:z66.enum(["default","explicit"]).optional()})}});import{z as z67}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","publishing","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z67.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_question","work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance","usage.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z67.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z67.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z67.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z67.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z67.object({enabled:z67.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z67.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z67.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z67.discriminatedUnion("kind",[z67.object({kind:z67.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z67.enum(["work_review","publishing","schedule","usage"]),enabled:z67.boolean(),source:PreferenceSourceSchema}).strict(),z67.object({kind:z67.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z67.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z67.object({kind:z67.literal("pause_toggle"),id:z67.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z67.literal("question_digest"),enabled:z67.boolean(),source:PreferenceSourceSchema,pausedUntil:z67.coerce.date().nullable()}).strict(),z67.object({kind:z67.literal("provider_subscription"),id:z67.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z67.literal("marketing"),name:z67.string(),description:z67.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z67.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z67.object({email:EmailNotificationPreferenceSchema,entries:z67.array(NotificationPreferenceEntrySchema),unavailableGroups:z67.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z67.object({enabled:z67.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z67.discriminatedUnion("kind",[z67.object({kind:z67.literal("toggle"),enabled:z67.boolean()}).strict(),z67.object({kind:z67.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z67.object({kind:z67.literal("pause_toggle"),enabled:z67.boolean(),pauseDays:z67.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."),z67.object({kind:z67.literal("provider_subscription"),enabled:z67.boolean()}).strict()])}});import{z as z68}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=z68.object({surface:SurfaceNameSchema,key:z68.string(),label:z68.string()}),InlineSchema=z68.object({text:z68.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z68.discriminatedUnion("type",[z68.object({type:z68.literal("paragraph"),content:z68.array(InlineSchema).max(24)}),z68.object({type:z68.literal("preview"),ref:DiffRefSchema,caption:z68.string().optional()}),z68.object({type:z68.literal("code"),code:z68.string(),lang:z68.string().optional(),caption:z68.string().optional()}),z68.object({type:z68.literal("risk"),level:z68.enum(["warning","error"]),content:z68.array(InlineSchema).max(24)}),z68.object({type:z68.literal("list"),items:z68.array(z68.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z68.object({headline:z68.string(),blocks:z68.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z68.object({summary:EnvDiffSummarySchema,fingerprint:z68.string(),generatedAt:z68.coerce.date(),cached:z68.boolean().optional(),credits:z68.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z69}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,PROJECT_ANALYTICS_TRACKING_STATES,ProjectAnalyticsTrackingStatusDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsTrackingStatusDTO,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=z69.object({date:z69.string(),visitors:z69.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z69.object({key:z69.string(),visitors:z69.number().int().nonnegative(),pageviews:z69.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z69.object({path:z69.string(),pageName:z69.string().nullable().optional(),visitors:z69.number().int().nonnegative(),pageviews:z69.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z69.object({preset:z69.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z69.string(),requestedTo:z69.string(),effectiveFrom:z69.string(),effectiveTo:z69.string(),isRetentionLimited:z69.boolean(),groupBy:z69.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z69.object({date:z69.string(),content:z69.string(),updatedAt:z69.string(),updatedByUserId:z69.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z69.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z69.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z69.number().int().nonnegative(),pageviews:z69.number().int().nonnegative(),botPageviews:z69.number().int().nonnegative(),botVisitors:z69.number().int().nonnegative(),bounceRate:z69.number().min(0).max(100),viewsPerVisit:z69.number().nonnegative(),averageVisitDurationSeconds:z69.number().nonnegative(),visitorsSeries:z69.array(ProjectDailyVisitorsDTOSchema),topPages:z69.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z69.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z69.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z69.object({state:z69.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z69.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z70}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=z70.object({id:z70.string(),email:z70.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z70.coerce.date(),createdAt:z70.coerce.date(),inviterUserId:z70.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z70.object({id:z70.string(),token:z70.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z70.object({success:z70.boolean(),projectId:z70.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z71}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=z71.object({id:z71.string(),name:z71.string(),image:z71.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z71.object({count:z71.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z71.object({counts:z71.object({signed_up:z71.int(),activated:z71.int()}),credits:z71.object({total:z71.int(),earned:z71.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z71.email(),emailVerified:z71.boolean(),createdAt:z71.coerce.date(),updatedAt:z71.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z72}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=z72.object({id:z72.string(),principalType:ProjectPrincipalTypeSchema,principalId:z72.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z72.coerce.date(),expiresAt:z72.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","knowledge:view","knowledge:edit","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=z72.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z72.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z72.record(z72.string(),z72.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z72.object({access:z72.array(ProjectAccessItemDTOSchema),invites:z72.array(ProjectInviteDTOSchema),organization:z72.object({name:z72.string().nullable(),logo:z72.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z72.object({success:z72.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z72.object({success:z72.boolean(),projectId:z72.uuid()}))}});import{z as z73}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=z73.object({publicationStatus:PublicationStatusSchema,appUrl:z73.string().nullable(),lastPublishedAt:z73.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z74}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=z74.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z74.object({branch:BranchSchema,revision:z74.string().min(1).max(64).nullable(),generation:z74.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z74.url().nullable()})}});import{z as z75}from"zod";var PreviewUpgradeRequiredSchema,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();PreviewUpgradeRequiredSchema=z75.object({code:z75.literal("PREVIEW_UPGRADE_REQUIRED"),message:z75.string(),currentVersion:z75.number().int().positive(),targetVersion:z75.literal(4)}),PreviewBridgePackageSchema=z75.object({name:z75.string().min(1),version:z75.string().min(1)}),PreviewBridgeCapabilitySchema=z75.object({integrated:z75.boolean(),packages:z75.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z75.object({url:z75.url(),expiresAt:z75.iso.datetime().nullable(),source:z75.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z75.object({name:z75.string().min(1),locator:z75.string().min(1).optional(),source:z75.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z75.object({kind:z75.literal("dependency_build_scripts_blocked"),packageManager:z75.enum(["pnpm","yarn","bun"]),packages:z75.array(z75.string()),targets:z75.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z75.string(),approvalKey:z75.string(),command:z75.string().optional(),approval:z75.object({id:z75.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z75.object({code:z75.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z75.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z75.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z75.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z75.object({message:z75.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z75.number().int().optional().catch(void 0),logTail:z75.array(z75.string()).optional().catch(void 0),logTailTruncated:z75.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z75.object({approvalId:z75.uuid()}),PreviewInstallPolicyApprovalEventSchema=z75.discriminatedUnion("type",[z75.object({type:z75.literal("progress"),step:z75.enum(["approval","install","restart","readiness"]),message:z75.string()}),z75.object({type:z75.literal("approved")}),z75.object({type:z75.literal("complete")}),z75.object({type:z75.literal("error"),code:z75.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z75.string()})])}});import{z as z76}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:z76.string(),slug:z76.string().nullable(),logo:z76.string().nullable(),metadata:z76.record(z76.string(),z76.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z76.object({id:z76.string(),name:z76.string(),email:z76.email(),image:z76.string().nullable()}),OrganizationMemberDTOSchema=z76.object({id:z76.string(),userId:z76.string(),organizationId:z76.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z76.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z77}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,AgentRuntimeOverageRefusalSchema,AgentRuntimeOverageDTOSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,OptionalSpendRefusalSchema,CreditPurchasePricingDTOSchema,CreditPurchasePricingDTO,PurchaseCreditsDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,PaymentRecoveryInvoiceDTOSchema,PaymentRecoveryDTOSchema,PaymentRecoveryDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,CreditPurchasePricingResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,PaymentRecoveryResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common2();init_create_dto();init_response();CancellationReasonCodeSchema=z77.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z77.object({reason:CancellationReasonCodeSchema,details:z77.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z77.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z77.object({offerVersion:z77.string().trim().min(1),unusedPremiumCreditAmount:z77.number().int().nonnegative(),amountDueNow:z77.number().int().nonnegative(),renewsOn:z77.string()}),PlanMigrationPreviewDTOSchema=z77.object({currency:z77.string().trim().min(1),unusedPremiumCreditAmount:z77.number().int().nonnegative(),amountDueNow:z77.number().int().nonnegative(),startsAt:z77.string(),renewsAt:z77.string(),nextRenewalAmount:z77.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z77.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z77.object({id:z77.string(),organizationId:z77.string(),legacySubscriptionId:z77.string(),offeredPlanCode:z77.string(),offeredPlanName:z77.string(),offeredPriceAmount:z77.number(),offeredCurrency:z77.string(),offerVersion:z77.string(),state:PlanMigrationStateSchema,checkoutToken:z77.string().nullable(),deadlineAt:z77.string(),transitions:z77.array(z77.object({event:z77.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z77.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z77.object({included:z77.number().optional(),unitPrice:z77.number().optional(),dailyCap:z77.number().nullable().optional()}),EntitlementsDTOSchema=z77.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z77.object({retentionDays:z77.number().int().positive(),canUseExtendedDateRanges:z77.boolean()}).optional(),history:z77.object({retentionDays:z77.number().int().positive()}).optional(),members:z77.object({canInvite:z77.boolean(),maxMembers:z77.number().int().positive().nullable()}).optional(),projects:z77.object({maxProjects:z77.number().int().positive().nullable()}).optional(),domains:z77.object({canUseCustomDomains:z77.boolean(),maxDomains:z77.number().int().nonnegative().nullable()}).optional(),media_storage:z77.object({limitBytes:z77.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z77.object({usedBytes:z77.number().int().nonnegative().nullable(),limitBytes:z77.number().int().nonnegative().nullable(),state:z77.enum(["ready","unavailable"]),measuredAt:z77.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z77.object({toPlanCode:TemplateCodeSchema,effectiveAt:z77.string(),scheduledAt:z77.string().nullable()}),AutomaticSpendStopDTOSchema=z77.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z77.string(),spendStopped:z77.boolean(),settlementEndsAt:z77.string()}),HostingOverageStatusDTOSchema=z77.object({state:z77.enum(["ready","unavailable"]),planCode:z77.string(),overageAvailable:z77.boolean(),overageEnabled:z77.boolean(),monthlyCapUsd:z77.number().int().positive().nullable(),agentRuntimeEnabled:z77.boolean(),agentRuntimeAvailable:z77.boolean(),periodStart:z77.iso.datetime().nullable(),periodEnd:z77.iso.datetime().nullable(),usedBytes:z77.number().nonnegative().nullable(),includedBytes:z77.number().nonnegative().nullable(),overageBytes:z77.number().nonnegative(),currentOverageAmountMicros:z77.number().nonnegative().nullable(),agentRuntimeAmountMicros:z77.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z77.number().nonnegative().nullable(),currency:z77.string().nullable(),status:z77.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z77.object({enabled:z77.boolean(),monthlyCapUsd:z77.number().int().positive().max(1e6).optional(),agentRuntimeEnabled:z77.boolean().optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z77.object({id:z77.string(),external_id:z77.string(),customerId:z77.string(),planId:z77.string(),planCode:z77.union([TemplateCodeSchema,z77.literal("Unknown")]),currentPeriod:z77.object({start:z77.string(),end:z77.string().nullable()}),cancelAt:z77.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z77.string(),nextPaymentAt:z77.string().nullable(),baseAmount:z77.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z77.object({totalCap:z77.number(),dailyCap:z77.number(),usedTotal:z77.number()}),CreditBalanceDTOSchema=z77.object({total:z77.number(),base:z77.number(),dailyBase:z77.number(),purchases:z77.number(),awards:z77.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z77.object({total:z77.number(),nearLimit:z77.boolean(),canChat:z77.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z77.object({dailyFreeAvailable:z77.number(),monthlyAvailable:z77.number(),purchasedAvailable:z77.number(),awardedAvailable:z77.number()}),ProjectDailyCreditAllowanceDTOSchema=z77.object({periodCap:z77.number(),dailyGrant:z77.number(),usedThisPeriod:z77.number(),remainingThisPeriod:z77.number()}),ProjectCreditBalanceDTOSchema=z77.object({projectId:z77.uuid(),organizationId:z77.string(),balance:z77.object({totalAvailable:z77.number(),nearLimit:z77.boolean(),canUseAi:z77.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z77.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z77.enum(["ok","near_limit","exhausted"]),AgentRuntimeOverageRefusalSchema=z77.enum(["plan_unknown","plan_cannot_fund","pending_plan_exit","consent_missing"]),AgentRuntimeOverageDTOSchema=z77.object({available:z77.boolean(),enabled:z77.boolean(),status:z77.enum(["included","paid","paused"]),pauseReason:AgentRuntimeOverageRefusalSchema.nullable(),rateUsdPerHour:z77.number().nonnegative().nullable(),monthlyCapUsd:z77.number().positive().nullable(),consentedAt:z77.coerce.date().nullable(),billableMs:z77.number().int().nonnegative(),paidRemainingMs:z77.number().int().nonnegative(),projectedAmountUsd:z77.number().nonnegative().nullable()}),AgentRuntimeUsageDTOSchema=z77.object({planCode:z77.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z77.object({source:z77.enum(["cached_subscription","free_fallback"]),settledMs:z77.number().int().nonnegative(),activeMs:z77.number().int().nonnegative(),reservedMs:z77.number().int().nonnegative().optional(),includedMs:z77.number().int().positive(),remainingMs:z77.number().int().nonnegative(),extraMs:z77.number().int().nonnegative(),resetsAt:z77.coerce.date()}),overage:AgentRuntimeOverageDTOSchema}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z77.discriminatedUnion("enabled",[z77.object({enabled:z77.literal(!0),thresholdUsd:z77.number().nonnegative(),refillAmountUsd:z77.number().nonnegative()}),z77.object({enabled:z77.literal(!1),thresholdUsd:z77.number().nonnegative().nullable(),refillAmountUsd:z77.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z77.discriminatedUnion("enabled",[z77.object({enabled:z77.literal(!0),thresholdUsd:z77.number().min(.01).multipleOf(.01),refillAmountUsd:z77.number().min(.01).multipleOf(.01),expectedRateToken:z77.string().trim().min(1).max(40)}).strict(),z77.object({enabled:z77.literal(!1),thresholdUsd:z77.number().min(.01).multipleOf(.01),expectedRateToken:z77.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z77.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z77.object({planCode:z77.union([TemplateCodeSchema,z77.literal("Unknown")]).nullable(),canPurchase:z77.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z77.number().int().positive(),minAmountUsd:z77.number().positive(),maxAmountUsd:z77.number().positive(),rateToken:z77.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z77.object({amountUsd:z77.number(),idempotencyKey:z77.string().trim().min(8).max(120),expectedRateToken:z77.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z77.object({invoiceId:z77.string(),newBalance:z77.int(),creditCount:z77.int(),amountUsd:z77.number(),creditsPerDollar:z77.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z77.object({url:z77.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z77.object({id:z77.string(),number:z77.string().nullable(),status:z77.string(),amountDue:z77.int(),currency:z77.string(),issuedAt:z77.string().nullable(),hostedInvoiceUrl:z77.string().nullable()}),PaymentRecoveryDTOSchema=z77.discriminatedUnion("status",[z77.object({status:z77.literal("eligible"),checkedAt:z77.string()}),z77.object({status:z77.literal("recovery_required"),checkedAt:z77.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z77.int().min(1)}),z77.object({status:z77.literal("unavailable"),checkedAt:z77.string(),reason:z77.enum(["provider_error","truncated","unattempted","foreign_invoice","unknown_status"])})]),PaymentRecoveryDTO=createDTO(PaymentRecoveryDTOSchema),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),PaymentRecoveryResponseSchema=createResponseSchema2(PaymentRecoveryDTOSchema)}});import{z as z78}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=z78.object({brand:z78.string(),last4:z78.string(),exp:z78.string(),isDefault:z78.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z79}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=z79.string().superRefine((path53,ctx)=>{let segments=path53.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=z79.object({type:z79.literal("renameField"),contentType:z79.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z79.object({enabled:z79.boolean()}).strict(),ContentFieldGroupSchema=z79.object({id:z79.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z79.string().min(1).max(255),default:z79.boolean().optional()}).strict(),ContentTypeDTOSchema=z79.object({id:z79.string(),name:z79.string(),label:z79.string(),isSingleton:z79.boolean(),i18n:ContentTypeI18nSchema,groups:z79.array(ContentFieldGroupSchema).default([]),fields:z79.record(z79.string(),FieldDefinitionSchema),createdAt:z79.string(),updatedAt:z79.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z79.object({contentTypes:z79.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z79.object({id:z79.string(),entryId:z79.string(),documentId:z79.string(),slug:z79.string(),locale:z79.string().optional(),createdAt:z79.string(),updatedAt:z79.string(),__fimo:z79.object({contentType:z79.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({limit:z79.number(),offset:z79.number(),total:z79.number(),hasMore:z79.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z79.object({contentType:z79.string(),count:z79.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z79.object({counts:z79.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z79.object({count:z79.number().int().nonnegative(),sourceLocale:z79.string(),targetLocale:z79.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z79.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z79.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z79.union([z79.string(),z79.number(),z79.boolean(),z79.null()]),entryWhereOperatorSchema2=z79.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z79.array(entryWhereScalarSchema2).optional(),$nin:z79.array(entryWhereScalarSchema2).optional(),$contains:z79.string().optional(),$startsWith:z79.string().optional(),$null:z79.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z79.record(z79.string(),z79.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z79.record(z79.string(),z79.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z79.object({data:z79.record(z79.string(),z79.unknown()),locale:z79.string().min(1).optional(),documentId:z79.uuid().optional()}),entryIdsSchema=z79.array(z79.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z79.object({sql:z79.string().min(1)}),BulkCreateEntriesRequestSchema=z79.object({entries:z79.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z79.union([z79.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z79.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z79.object({updates:z79.array(z79.object({id:z79.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z79.union([z79.object({ids:entryIdsSchema,locale:z79.string().min(1).optional()}),z79.object({where:EntryWhereSchema2,locale:z79.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z79.object({data:z79.array(z79.record(z79.string(),z79.unknown())),meta:z79.object({rowCount:z79.number().int().nonnegative(),truncated:z79.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({created:z79.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({updated:z79.number().int().nonnegative(),missing:z79.array(z79.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z79.object({data:z79.array(EntryDTOSchema2),meta:z79.object({deleted:z79.number().int().nonnegative(),missing:z79.array(z79.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z80}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z80.object({index:z80.number().int().nonnegative(),contentType:z80.string(),field:z80.string(),value:z80.string(),against:z80.enum(["stored","batch"]),ownerDocumentId:z80.uuid().optional(),ownerIndex:z80.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z80.object({code:z80.literal("unique_conflict"),message:z80.string(),conflicts:z80.array(UniqueConflictSchema),truncated:z80.boolean().optional()})}});import{z as z81}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=z81.object({kind:z81.literal("unique_conflict"),contentType:z81.string(),field:z81.string(),value:z81.string(),documentCount:z81.number().int().positive(),documentIds:z81.array(z81.uuid()),documentIdsTruncated:z81.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z81.object({code:z81.literal("schema_transition_rejected"),message:z81.string(),issues:z81.array(SchemaTransitionIssueSchema),truncated:z81.boolean().optional()})}});import{z as z82}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=z82.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z82.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z82.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z82.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z82.object({field:CmsFieldNameSchema,direction:z82.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z82.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z82.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z82.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z82.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z82.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z83}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=z83.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z84}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=z84.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z84.object({event:ClientTrackedEventSchema,properties:z84.record(z84.string(),z84.unknown()).default({})})}});import{z as z85}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=z85.object({id:z85.string(),name:z85.string()}),AssetDTOSchema2=z85.object({id:z85.string(),name:z85.string(),type:AssetTypeSchema,originalFileName:z85.string().nullable(),parentId:z85.string().nullable(),mimeType:z85.string().nullable(),fileSize:z85.number().nullable(),url:z85.string().nullable(),storageKey:z85.string().nullable(),createdAt:z85.string(),updatedAt:z85.string(),altText:z85.string().nullable().optional(),caption:z85.string().nullable().optional(),aiCaption:z85.string().nullable().optional(),aiAltText:z85.string().nullable().optional(),aiTags:z85.array(z85.string()).nullable().optional(),aiPrimaryColor:z85.string().nullable().optional(),aiProcessingStatus:z85.string().nullable().optional(),width:z85.number().nullable().optional(),height:z85.number().nullable().optional(),path:z85.array(AssetPathItemSchema).optional(),hasChildren:z85.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z85.lazy(()=>z85.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z85.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z85.object({error:z85.string(),code:z85.literal("media_storage_limit_exceeded"),usedBytes:z85.number().int().nonnegative(),limitBytes:z85.number().int().positive(),incomingBytes:z85.number().int().nonnegative()}),AssetReferenceScopeSchema=z85.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z85.object({assetIds:z85.array(z85.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z85.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z85.object({totalFiles:z85.number().int().nonnegative(),checkedFiles:z85.number().int().nonnegative(),limit:z85.number().int().positive()}),AssetReferenceFindingDTOSchema=z85.object({assetId:z85.uuid(),entryId:z85.string(),documentId:z85.string(),contentType:z85.string(),locale:z85.string().nullable(),slug:z85.string(),fieldPath:z85.string()}),AssetReferenceScopeResultDTOSchema=z85.object({scope:AssetReferenceScopeSchema,label:z85.string(),state:z85.enum(["available","not-published","failed"]),coverage:z85.enum(["complete","partial","failed"]),referenceCount:z85.number().int().nonnegative().optional(),codeReferenceCount:z85.number().int().nonnegative().optional(),referencedAssetIds:z85.array(z85.uuid()).optional(),references:z85.array(AssetReferenceFindingDTOSchema),reason:z85.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z85.discriminatedUnion("type",[z85.object({type:z85.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z85.object({type:z85.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z85.object({type:z85.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z85.object({replacementAssetId:z85.uuid()}),AssetReferenceReplacementResultSchema=z85.object({referencesReplaced:z85.number().int().nonnegative(),entriesChanged:z85.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z85.object({referencesReplaced:z85.number().int().nonnegative(),filesChanged:z85.number().int().nonnegative(),commitSha:z85.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z85.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=z85.object({error:z85.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z85.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=z85.object({intent:AssetRemovalIntentSchema,assetIds:z85.array(z85.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z85.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=z85.object({id:z85.uuid(),intent:AssetRemovalIntentSchema,assetIds:z85.array(z85.uuid()),replacementAssetId:z85.uuid().nullable(),expiresAt:z85.iso.datetime(),undoable:z85.boolean(),requestedByMe:z85.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z85.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z85.object({error:z85.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z86}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z86.object({key:z86.string(),value:z86.string().optional(),defaultValue:z86.string(),locale:z86.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z87}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=z87.object({id:z87.string(),name:z87.string(),type:z87.enum(["file","folder"]),path:z87.string(),children:z87.lazy(()=>z87.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z87.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z87.object({path:z87.string(),exists:z87.boolean(),type:z87.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z88}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=z88.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z88.object({minLength:z88.number().optional(),maxLength:z88.number().optional(),min:z88.number().optional(),max:z88.number().optional(),pattern:z88.string().optional(),maxFileSize:z88.number().optional(),accept:z88.array(z88.string()).optional()}),FormFieldSchema=z88.object({type:FormFieldTypeSchema,label:z88.string(),placeholder:z88.string().optional(),required:z88.boolean().optional(),defaultValue:z88.string().optional(),options:z88.array(z88.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z88.record(z88.string(),FormFieldSchema),FormContentSchema2=z88.object({name:z88.string().min(1).max(255),label:z88.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 z89}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,ChatRoutineCreateSchema,ChatRoutineUpdateSchema,ChatRoutineRefusalReasonSchema,ChatRoutineRefusalDTOSchema,ChatRoutineRunStatusSchema,ChatRoutineRunTriggerSchema,ChatRoutineRunStartedBySchema,ChatRoutineRunDTOSchema,ChatRoutineRunListDTOSchema,ChatRoutineRunRequestSchema,ChatRoutineRunOutcomeDTOSchema,init_chat_routine_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-routine.dto.js"(){"use strict";ChatRoutineCronSchema=z89.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z89.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z89.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z89.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z89.string().trim().min(1).max(2e4),ChatRoutineTriggersDTOSchema=z89.object({manual:z89.literal(!0),schedule:ChatRoutineScheduleSchema.nullable()}),ChatRoutineRunOutcomeSchema=z89.enum(["quiet","reported","decision","failed","running"]),ChatRoutineReportSchema=z89.object({message:z89.string().trim().min(1).max(2e4),decision:z89.boolean().optional()}),ChatRoutineDTOSchema=z89.object({id:z89.string().uuid(),threadId:z89.string().uuid(),runThreadId:z89.string().uuid(),name:z89.string(),instructions:z89.string(),triggers:ChatRoutineTriggersDTOSchema,paused:z89.boolean(),nextRunAt:z89.string().nullable(),lastRunAt:z89.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),createdAt:z89.string(),updatedAt:z89.string()}),ChatRoutineListDTOSchema=z89.object({routines:z89.array(ChatRoutineDTOSchema)}),ChatRoutineCreateSchema=z89.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional()}),ChatRoutineUpdateSchema=z89.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),paused:z89.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z89.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent"]),ChatRoutineRefusalDTOSchema=z89.object({message:z89.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z89.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z89.enum(["schedule","hand"]),ChatRoutineRunStartedBySchema=z89.object({kind:z89.enum(["person","agent"]),name:z89.string().nullable()}),ChatRoutineRunDTOSchema=z89.object({messageId:z89.string().uuid(),invocationId:z89.string().uuid().nullable(),startedAt:z89.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z89.string().nullable()}),ChatRoutineRunListDTOSchema=z89.object({runs:z89.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z89.object({message:z89.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z89.object({kind:z89.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z89.string().uuid().nullable()})}});import{z as z90}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,ProjectChatDTOSchema,ProjectChatListDTOSchema,ProjectChatCreatedDTOSchema,ProjectChatTitleSchema,ProjectChatCreateSchema,ProjectChatUpdateSchema,ChatTemplateRoutineScheduleDTOSchema,ChatTemplateRoutineDTOSchema,ChatTemplateDTOSchema,ChatTemplateListDTOSchema,ProjectChatStateSchema,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_chat_portrait();init_create_dto();init_response();init_chat_routine_dto();init_project_dto();ChatMessageListDTOSchema=z90.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z90.object({items:z90.array(ProjectMessagePublicDTOSchema),nextCursor:z90.string().nullable()}),ChatLiveTurnDTOSchema=z90.object({invocationId:z90.string(),step:z90.enum(["preparing","working","compacting","merging"]),startedAt:z90.string(),continuesInvocationId:z90.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z90.object({threadId:z90.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z90.object({kind:z90.enum(["person","agent","routine","system"]),id:z90.string().nullable()}),ChatThreadMessageDTOSchema=z90.object({id:z90.string(),role:z90.enum(["user","assistant"]),parts:z90.array(z90.unknown()),metadata:z90.record(z90.string(),z90.unknown()).nullable(),versionId:z90.string().nullable().optional(),createdAt:z90.date().transform(value=>value.toISOString()),providerMessageId:z90.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z90.string().nullable().optional(),invocationStatus:z90.string().nullable().optional(),invocationTerminalReason:z90.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z90.object({id:z90.string(),parts:z90.array(z90.unknown()),metadata:z90.record(z90.string(),z90.unknown()).nullable(),providerMessageId:z90.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z90.boolean(),queuedAt:z90.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z90.object({type:z90.literal("merge_conflict"),merge:z90.object({mergeId:z90.string().uuid(),projectId:z90.string(),fromBranch:z90.string(),toBranch:z90.string()}),publishAfterMerge:z90.boolean()}),ChatThreadMessagesPageDTOSchema=z90.object({threadId:z90.string().nullable(),title:z90.string().nullable(),messages:z90.array(ChatThreadMessageDTOSchema),nextCursor:z90.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z90.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z90.boolean().optional()}),ChatReplayOutcomeDTOSchema=z90.object({kind:z90.literal("replay"),threadId:z90.string(),userMessageId:z90.string()}),ChatQueuedOutcomeDTOSchema=z90.object({kind:z90.literal("queued"),threadId:z90.string(),userMessageId:z90.string(),blockingRootId:z90.string().optional()}),ChatBusyOutcomeDTOSchema=z90.object({kind:z90.literal("busy"),threadId:z90.string(),userMessageId:z90.string(),blockingRootId:z90.string().optional()}),ChatRefusedOutcomeDTOSchema=z90.object({kind:z90.literal("refused"),threadId:z90.string(),userMessageId:z90.string(),refusedInvocationId:z90.string(),terminalReason:z90.string()}),ChatNonStreamingOutcomeDTOSchema=z90.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z90.enum(["chat","agent","routine"]),ProjectChatCreatableKindSchema=z90.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z90.object({quietRuns:z90.number().int().nonnegative(),since:z90.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z90.string().nullable(),nextRunAt:z90.string().nullable(),paused:z90.boolean(),firstRunAt:z90.string().nullable()}),ProjectChatDescriptionSchema=z90.string().trim().max(2e3),ProjectChatDTOSchema=z90.object({id:z90.string().uuid(),kind:ProjectChatKindSchema,title:z90.string().nullable(),description:z90.string().nullable(),template:z90.string().nullable(),parentThreadId:z90.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z90.string(),lastMessageAt:z90.string().nullable(),preview:z90.string().nullable(),running:z90.boolean(),awaitingAnswer:z90.boolean(),unread:z90.boolean(),pinned:z90.boolean(),archived:z90.boolean(),muted:z90.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z90.object({chats:z90.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z90.object({id:z90.string().uuid()}),ProjectChatTitleSchema=z90.string().trim().min(1).max(120),ProjectChatCreateSchema=z90.object({id:z90.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z90.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema}).partial().refine(create=>create.template===void 0||create.kind===void 0&&create.title===void 0&&create.description===void 0,"A template brings its own kind, title and description"),ProjectChatUpdateSchema=z90.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.portrait!==void 0,"Set a title, a description or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z90.object({cron:z90.string()}),ChatTemplateRoutineDTOSchema=z90.object({name:z90.string(),instructions:z90.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable()}),ChatTemplateDTOSchema=z90.object({id:z90.string(),name:z90.string(),summary:z90.string(),description:z90.string(),portrait:ChatPortraitSchema,routines:z90.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z90.object({templates:z90.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z90.object({read:z90.boolean(),pinned:z90.boolean(),archived:z90.boolean(),muted:z90.boolean()}).partial().refine(state=>Object.keys(state).length>0,"Set at least one of read, pinned, archived or muted"),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema)}});import{z as z91}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=z91.object({url:z91.string().url(),key:z91.string(),size:z91.number(),contentType:z91.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z92}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=z92.object({canAccess:z92.boolean(),permissions:z92.record(z92.string(),z92.boolean()),role:z92.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z93}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:z93.string().trim().default(""),sort:z93.enum(["recent","name","relevance"]).default("recent"),category:z93.string().optional()})}});import{z as z94}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=z94.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z94.enum(["fimo","external"]),PaymentStatusSchema=z94.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z94.object({id:z94.string().uuid(),domain:z94.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z94.boolean(),price:z94.number().int().nullable(),renewalPrice:z94.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z94.string().nullable(),failureReason:z94.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z94.object({domain:z94.string(),available:z94.boolean(),premium:z94.boolean(),price:z94.number().nullable(),renewalPrice:z94.number().nullable(),purchaseType:z94.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z94.object({domain:z94.string(),price:z94.number().nullable(),renewalPrice:z94.number().nullable(),premium:z94.boolean(),allowedYears:z94.array(z94.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z94.object({firstName:z94.string().max(100),lastName:z94.string().max(100),companyName:z94.string().max(100).optional(),address1:z94.string().max(255),address2:z94.string().max(255).optional(),city:z94.string().max(100),state:z94.string().max(100),zip:z94.string().max(20),country:z94.string().max(2),phone:z94.string().max(30),email:z94.union([z94.string().email().max(255),z94.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z94.object({firstName:z94.string().min(1).max(100),lastName:z94.string().min(1).max(100),companyName:z94.string().max(100).optional(),address1:z94.string().min(1).max(255),address2:z94.string().max(255).optional(),city:z94.string().min(1).max(100),state:z94.string().min(1).max(100),zip:z94.string().min(1).max(20),country:z94.string().min(1).max(2),phone:z94.string().min(1).max(30),email:z94.string().email().max(255)}),SearchDomainsRequestSchema=z94.object({keyword:z94.string().min(1).max(100),tldFilter:z94.array(z94.string()).optional()}),CheckAvailabilityRequestSchema=z94.object({domains:z94.array(z94.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=z94.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z94.object({domain:DomainNameSchema,years:z94.number().int().min(1).max(10).optional().default(3),autoRenew:z94.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z94.object({autoRenew:z94.boolean().optional()}),RenewDomainRequestSchema=z94.object({years:z94.number().int().min(1).max(10).optional().default(1),autoRenew:z94.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z94.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z94.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z94.object({verified:z94.boolean(),email:z94.string().nullable(),verifyBy:z94.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z95}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=z95.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=z95.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=z95.object({txtName:z95.string().nullable().optional(),txtValue:z95.string().nullable().optional(),httpUrl:z95.string().nullable().optional(),httpBody:z95.string().nullable().optional(),cname:z95.string().nullable().optional(),cnameTarget:z95.string().nullable().optional()}),SSLValidationErrorSchema=z95.object({message:z95.string()}),OwnershipVerificationSchema=z95.object({type:z95.string(),name:z95.string(),value:z95.string()}),ProjectDomainSSLDTOSchema=z95.object({status:z95.string(),method:z95.string().nullable(),type:z95.string().nullable(),validationRecords:z95.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z95.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z95.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z95.enum(["subdomain","apex"]),RedirectConfigSchema=z95.object({type:z95.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z95.string()}).nullable().optional(),ProjectDomainDTOSchema=z95.object({id:z95.string(),hostname:z95.string(),status:z95.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z95.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z95.string(),scdCnameTarget:z95.string().optional(),apexTargets:z95.array(z95.string()),dnsAutoConfigured:z95.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z95.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z95.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z95.object({hostname:z95.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:z95.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z95.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z95.object({available:z95.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z95.object({success:z95.boolean(),hostname:z95.string()}))}});import{z as z96}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=z96.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z96.object({available:z96.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z96.object({slug:z96.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z96.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z96.object({subdomain:z96.string(),subdomainUpdatedAt:z96.coerce.date()})),SubdomainSuggestionsQuerySchema=z96.object({base:z96.string().max(100).optional(),max:z96.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z96.object({suggestions:z96.array(z96.string())}))}});import{z as z97}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=z97.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z97.object({code:ProjectTransferBlockerCodeSchema,message:z97.string(),count:z97.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z97.object({targetOrganizationId:z97.string().min(1)}),ProjectTransferResultDTO=createDTO(z97.object({projectId:z97.string(),sourceOrganizationId:z97.string(),targetOrganizationId:z97.string(),movedThreads:z97.number().int().nonnegative(),revokedInvites:z97.number().int().nonnegative(),revokedGrants:z97.number().int().nonnegative(),preservedGrants:z97.number().int().nonnegative(),warnings:z97.array(z97.string())}))}});import{z as z98}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=z98.object({translated:z98.number().int().nonnegative(),total:z98.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z98.object({locale:z98.string(),isDefault:z98.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z98.object({defaultLocale:z98.string(),locales:z98.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z98.object({locale:z98.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z98.object({locale:z98.string().min(1).max(40)}),ProjectLocaleMutationSchema=z98.object({locale:z98.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z98.object({locale:z98.string(),entriesDeleted:z98.number().int().nonnegative(),labelsDeleted:z98.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z99}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=z99.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z99.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=z99.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z99.number(),credits:z99.number().optional(),billingMode:z99.enum(["fimo-credits","provider-account"]).optional(),confidence:z99.enum(["exact","estimated","metered"]),basis:z99.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z100}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=z100.object({options:z100.record(z100.string(),z100.unknown()),name:z100.string().optional(),parentId:z100.string().nullable().optional(),altText:z100.string().optional(),caption:z100.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z100.string().min(1).optional(),model:z100.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=z100.object({jobId:z100.string(),status:z100.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z100.string().nullable().optional(),credits:z100.number().optional(),costUsd:z100.number().optional(),billingMode:z100.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z100.object({error:z100.string(),code:z100.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:z100.array(GenerationTaskIdSchema).optional(),availableModels:z100.array(z100.string()).optional(),issues:z100.array(z100.unknown()).optional()})}});import{z as z101}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=z101.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z101.object({name:z101.string(),key:z101.string(),description:z101.string(),type:FlagTypeSchema,required:z101.boolean(),defaultValue:z101.unknown().optional(),enumValues:z101.array(z101.string()).optional(),isArray:z101.boolean()}),AssetModelPriceSchema=z101.object({unitPrice:z101.number(),unit:z101.string(),confidence:z101.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z101.object({id:z101.string(),shortName:z101.string(),provider:z101.string(),source:z101.string(),modality:z101.enum(["image","video","audio"]),tags:z101.array(z101.string()),displayName:z101.string(),description:z101.string(),flags:z101.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z101.object({model:z101.string(),costUsd:z101.number(),credits:z101.number(),billingMode:z101.enum(["fimo-credits","provider-account"]),confidence:z101.enum(["exact","estimated","metered"]),basis:z101.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z102}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=z102.object({tourId:z102.string(),version:z102.string(),status:z102.string(),completedAt:z102.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z102.array(UserTourDTOSchema))}});import{z as z103}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=z103.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z103.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z103.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z103.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z103.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z103.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z103.enum(["user","agent","system"]),SupportReportTagSchema=z103.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z103.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z103.object({organization:z103.object({id:z103.string().trim().min(1).max(255),name:z103.string().trim().max(240).optional()}),project:z103.object({id:z103.uuid(),name:z103.string().trim().max(240).optional(),createdAt:z103.coerce.date().optional()}).optional(),environment:z103.string().trim().max(255).optional(),clientVersion:z103.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z103.object({message:z103.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z103.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z103.string().trim().max(200).optional(),limit:z103.coerce.number().int().min(1).max(100).default(50),offset:z103.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z103.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z103.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z103.uuid().nullable().optional(),note:z103.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=z103.object({message:z103.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z103.object({kind:SupportReportLinkKindSchema,label:z103.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z103.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z103.object({kind:SupportReportActorKindSchema,id:z103.string().nullable(),name:z103.string().nullable()}),SupportReportLinkDTOSchema=z103.object({id:z103.uuid(),kind:SupportReportLinkKindSchema,label:z103.string(),url:SupportReportHttpUrlSchema,externalId:z103.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z103.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z103.object({id:z103.uuid(),kind:SupportReportEventKindSchema,body:z103.string().nullable(),metadata:z103.record(z103.string(),z103.unknown()),actor:SupportReportActorDTOSchema,createdAt:z103.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z103.object({id:z103.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z103.array(z103.string()),source:SupportReportSourceSchema,message:z103.string(),reporter:z103.object({id:z103.string().nullable(),name:z103.string().nullable(),email:z103.string().nullable()}),organization:z103.object({id:z103.string().nullable(),name:z103.string()}),project:z103.object({id:z103.uuid().nullable(),name:z103.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z103.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z103.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z103.string().nullable(),deliveredAt:z103.coerce.date().nullable()}).nullable(),duplicateOfReportId:z103.uuid().nullable(),resolvedAt:z103.coerce.date().nullable(),createdAt:z103.coerce.date(),updatedAt:z103.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z103.string().nullable(),clientVersion:z103.string().nullable(),links:z103.array(SupportReportLinkDTOSchema),events:z103.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z103.object({reports:z103.array(SupportReportSummaryDTOSchema),total:z103.number().int().nonnegative(),statusCounts:z103.object({new:z103.number().int().nonnegative(),in_progress:z103.number().int().nonnegative(),waiting:z103.number().int().nonnegative(),resolved:z103.number().int().nonnegative(),duplicate:z103.number().int().nonnegative(),irrelevant:z103.number().int().nonnegative(),ignored:z103.number().int().nonnegative()}),limit:z103.number().int().positive(),offset:z103.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z103.object({id:z103.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z103.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z104}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=z104.iso.datetime({offset:!0}).pipe(z104.coerce.date()),OpsRecentChatInputSchema=z104.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z104.string().trim().min(1).max(255).optional(),limit:z104.coerce.number().int().min(1).max(200).default(100),cursor:z104.string().trim().min(1).max(2e3).optional(),slim:z104.boolean().default(!0),reason:z104.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=z104.object({id:z104.string(),threadId:z104.string(),providerMessageId:z104.string().nullable(),invocationId:z104.string().nullable(),env:z104.string().nullable(),role:z104.string(),parts:z104.array(z104.record(z104.string(),z104.unknown())),metadata:z104.object({status:z104.string().optional(),traceUrl:z104.string().optional(),externalFileChanges:z104.array(z104.unknown()).optional()}),stats:z104.object({toolCount:z104.number().int().nonnegative(),failedToolCount:z104.number().int().nonnegative()}),createdAt:z104.iso.datetime({offset:!0}),project:z104.object({id:z104.string(),name:z104.string(),displayName:z104.string().nullable(),organizationId:z104.string().nullable()})}),OpsRecentChatResponseSchema=z104.object({target:z104.object({backendProfile:OpsBackendProfileSchema,projectEnv:z104.string().nullable()}),window:z104.object({from:z104.iso.datetime({offset:!0}),to:z104.iso.datetime({offset:!0})}),messages:z104.object({items:z104.array(OpsRecentChatMessageSchema),nextCursor:z104.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z105}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=z105.object({backendProfile:OpsBackendProfileSchema,provider:z105.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z105.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z105.object({backendProfile:OpsBackendProfileSchema,provider:z105.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z105.literal(!1),reason:z105.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z106}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=z106.object({packageManager:z106.string().trim().min(1).max(200).nullable(),trackedLockfiles:z106.array(z106.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z106.string().trim().min(1)}),OpsProjectPackageManagerSchema=z106.object({target:z106.object({backendProfile:OpsBackendProfileSchema,projectId:z106.uuid(),projectEnv:z106.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z107}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=z107.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=z107.object({branch:BranchSchema,sessionId:z107.uuid()}),OpsAgentBranchDiscardPlanInputSchema=z107.object({branches:OpsAgentBranchAllowlistSchema,reason:z107.string().trim().min(1).max(1e3),recoveredOwners:z107.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:z107.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=z107.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z108}from"zod";function createAgentRunWebhookEventDataSchema(status){return z108.object({run:z108.object({id:z108.string(),agentName:z108.string(),trigger:z108.string(),status:z108.literal(status),startedAt:z108.string().nullable(),finishedAt:z108.string().nullable(),reason:z108.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=z108.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z108.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z108.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z108.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z108.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z108.object({reason:WebhookEntryChangeReasonSchema,operationId:z108.string().optional(),batch:z108.object({index:z108.number().int().positive(),total:z108.number().int().positive()}).optional(),changes:z108.array(z108.object({action:WebhookEntryChangeActionSchema,contentType:z108.string(),id:z108.string(),documentId:z108.string(),locale:z108.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z108.object({form:z108.object({id:z108.string(),label:z108.string()}),submission:z108.object({id:z108.string(),data:z108.record(z108.string(),z108.unknown()),submittedAt:z108.string()})}),PublishStartedWebhookEventDataSchema=z108.object({publication:z108.object({status:z108.literal("publishing"),startedAt:z108.string()})}),PublishSucceededWebhookEventDataSchema=z108.object({publication:z108.object({status:z108.literal("published"),url:z108.string(),publishedAt:z108.string(),firstPublish:z108.boolean()})}),PublishFailedWebhookEventDataSchema=z108.object({publication:z108.object({status:z108.literal("failed"),reason:z108.string()})}),PublishUnpublishedWebhookEventDataSchema=z108.object({publication:z108.object({previousUrl:z108.string(),unpublishedAt:z108.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z108.object({review:z108.object({runId:z108.string(),agentName:z108.string(),reason:z108.string()}),source:z108.object({branch:z108.string(),revision:z108.string(),anchorBranch:z108.string()})}),AgentReviewResolvedWebhookEventDataSchema=z108.object({review:z108.object({id:z108.string(),runId:z108.string(),agentName:z108.string(),resolution:z108.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z108.object({report:z108.object({weekStart:z108.string(),weekEnd:z108.string(),pageviews:z108.number(),visitors:z108.number(),previousPageviews:z108.number(),previousVisitors:z108.number()})}),MediaAssetWebhookEventDataSchema=z108.object({id:z108.string().nullable(),name:z108.string().nullable(),type:z108.string(),mimeType:z108.string().nullable(),fileSize:z108.number().nullable()}),MediaUploadedWebhookEventDataSchema=z108.object({asset:MediaAssetWebhookEventDataSchema,operation:z108.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z108.object({asset:MediaAssetWebhookEventDataSchema,operation:z108.literal("updated")}),MediaDeletedWebhookEventDataSchema=z108.object({asset:MediaAssetWebhookEventDataSchema,operation:z108.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z108.object({domain:z108.object({id:z108.string(),hostname:z108.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z108.object({domain:z108.object({id:z108.string(),hostname:z108.string()})}),LabelChangedWebhookEventDataSchema=z108.object({changes:z108.array(z108.object({action:z108.enum(["created","updated","deleted"]),key:z108.string(),locale:z108.string(),value:z108.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z108.object({locale:z108.object({code:z108.string(),isDefault:z108.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z108.object({locale:z108.object({code:z108.string(),previousCode:z108.string()})}),LocaleDeletedWebhookEventDataSchema=z108.object({locale:z108.object({code:z108.string(),entriesDeleted:z108.number().int().nonnegative(),labelsDeleted:z108.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z108.object({environment:z108.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z108.object({environment:z108.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z108.object({merge:z108.object({id:z108.string(),from:BranchSchema,to:BranchSchema,applied:z108.array(z108.object({surface:SurfaceNameSchema,count:z108.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z108.object({branch:z108.object({name:BranchSchema}),version:z108.object({versionId:z108.uuid(),name:z108.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=z108.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z108.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z108.discriminatedUnion("source",[z108.object({source:z108.literal("literal"),value:z108.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z108.object({source:z108.literal("secret"),key:z108.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z108.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z108.object({name:z108.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z108.object({name:z108.string(),source:z108.enum(["literal","secret"]),secretKey:z108.string().nullable(),secretPrefix:z108.string().nullable(),configured:z108.literal(!0)}),WebhookFilterSchema=z108.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z108.string().min(1).max(255).optional(),agentName:z108.string().min(1).max(120).optional(),mediaType:z108.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z108.string().min(1).max(255).optional(),locale:z108.string().min(1).max(120).optional()}),JsonValueSchema=z108.lazy(()=>z108.union([z108.string(),z108.number(),z108.boolean(),z108.null(),z108.array(JsonValueSchema),z108.record(z108.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z108.object({name:z108.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z108.url(),enabled:z108.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z108.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z108.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z108.object({name:z108.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z108.url().optional(),enabled:z108.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z108.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z108.boolean().optional()}),TestProjectWebhookRequestSchema=z108.object({eventType:WebhookEventTypeSchema.optional(),data:z108.record(z108.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z108.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z108.uuid(),name:z108.string(),eventType:WebhookEventTypeSchema,enabled:z108.boolean(),destination:z108.object({host:z108.string(),maskedUrl:z108.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z108.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z108.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z108.coerce.date().nullable(),deliveryStats24h:z108.object({succeeded:z108.number().int().nonnegative(),failed:z108.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z108.uuid(),projectId:z108.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z108.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z108.number().int().positive(),test:z108.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z108.number().int().nonnegative(),responseStatus:z108.number().int().nullable(),lastErrorCode:z108.string().nullable(),lastErrorMessage:z108.string().nullable(),payloadAvailable:z108.boolean(),destination:z108.object({host:z108.string(),maskedUrl:z108.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z108.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z108.string().nullable(),qstashMessageId:z108.string().nullable(),deliveredAt:z108.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z108.object({items:z108.array(WebhookDeliveryDTOSchema),pagination:z108.object({page:z108.number().int().positive(),limit:z108.number().int().positive(),total:z108.number().int().nonnegative(),totalPages:z108.number().int().positive(),hasMore:z108.boolean()}),stats:z108.object({total:z108.number().int().nonnegative(),succeeded:z108.number().int().nonnegative(),failed:z108.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z108.object({id:z108.uuid(),deliveryId:z108.uuid(),attempt:z108.number().int().positive(),status:z108.enum(["delivering","succeeded","failed"]),responseStatus:z108.number().int().nullable(),durationMs:z108.number().int().nonnegative(),responseExcerpt:z108.string().nullable(),errorCode:z108.string().nullable(),errorMessage:z108.string().nullable(),createdAt:z108.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z108.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z108.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z109}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=z109.object({key:z109.literal("fimo-2"),enabled:z109.boolean(),dismissed:z109.boolean().default(!1),interacted:z109.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z110}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteReportSchema,SitePriceTierSchema,BusinessBriefSchema,SiteInterviewDraftSchema,SiteInterviewAnswersSchema,SiteInterviewStepSchema,SiteInterviewSchema,AnswerSiteInterviewRequestSchema,StartSiteOnboardingRequestSchema,StartSiteOnboardingResponseSchema,SiteOnboardingRefusedResponseSchema,SiteOnboardingStateSchema,SiteOnboardingStateDTO,SiteOnboardingStateResponseSchema,RetrySiteOnboardingRequestSchema,SiteOnboardingOutcomeSchema,AdminSiteOnboardingsQuerySchema,AdminSiteOnboardingDTOSchema,AdminSiteOnboardingDTO,AdminSiteOnboardingsResponseSchema,AdminSiteOnboardingStatsSchema,AdminSiteOnboardingStatsResponseSchema,init_site_onboarding_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/site-onboarding.dto.js"(){"use strict";init_create_dto();init_response();SiteOnboardingStageSchema=z110.enum(["scanning","interviewing","reporting","open","expired"]),SiteScanStatusSchema=z110.enum(["running","done","failed"]),SiteCloneStatusSchema=z110.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z110.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z110.object({code:SiteRefusalCodeSchema,suggestedUrl:z110.string().nullable()}),SiteCheckGroupSchema=z110.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z110.enum(["seo","geo"]),SITE_CHECKS=[{id:"robots_txt",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap_lastmod",group:"discovery",scores:["seo","geo"],weight:1},{id:"broken_links",group:"discovery",scores:["seo"],weight:2},{id:"internal_nofollow",group:"discovery",scores:["seo"],weight:1},{id:"blocked_from_crawling",group:"discovery",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"status_4xx",group:"indexing",scores:["seo","geo"],weight:2,cap:{seo:10,geo:10}},{id:"status_5xx",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:10,geo:10}},{id:"https_to_http",group:"indexing",scores:["seo"],weight:1,cap:{seo:50}},{id:"canonical",group:"indexing",scores:["seo"],weight:1},{id:"noindex",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"hreflang",group:"indexing",scores:["seo"],weight:1},{id:"missing_page",group:"indexing",scores:["seo","geo"],weight:1,cap:{seo:80,geo:80}},{id:"ai_bots_robots",group:"ai_crawlers",scores:["geo"],weight:3,cap:{geo:30}},{id:"ai_bot_access",group:"ai_crawlers",scores:["geo"],weight:2,cap:{geo:40}},{id:"llms_txt",group:"ai_crawlers",scores:["geo"],weight:1},{id:"server_rendering",group:"rendering",scores:["geo"],weight:3},{id:"semantic_html",group:"rendering",scores:["seo","geo"],weight:2},{id:"markdown_pages",group:"rendering",scores:["geo"],weight:1},{id:"markdown_alternate",group:"rendering",scores:["geo"],weight:.5},{id:"markdown_index",group:"rendering",scores:["geo"],weight:.5},{id:"meta_title",group:"metadata",scores:["seo"],weight:2},{id:"meta_description",group:"metadata",scores:["seo"],weight:2},{id:"structured_data",group:"metadata",scores:["seo","geo"],weight:2},{id:"organization_schema",group:"metadata",scores:["geo"],weight:2},{id:"entity_links",group:"metadata",scores:["geo"],weight:1},{id:"metadata_completeness",group:"metadata",scores:["seo","geo"],weight:2},{id:"trust_pages",group:"metadata",scores:["geo"],weight:2},{id:"word_count",group:"content",scores:["seo","geo"],weight:2},{id:"text_ratio",group:"content",scores:["seo"],weight:1},{id:"h1",group:"content",scores:["seo"],weight:2},{id:"image_alt",group:"content",scores:["seo","geo"],weight:1},{id:"broken_images",group:"content",scores:["seo"],weight:1},{id:"empty_link_text",group:"content",scores:["seo","geo"],weight:1},{id:"page_load",group:"speed",scores:["seo"],weight:3},{id:"unminified_assets",group:"speed",scores:["seo"],weight:1}],SiteCheckIdSchema=z110.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z110.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z110.record(z110.string(),z110.union([z110.string(),z110.number(),z110.boolean(),z110.array(z110.string())])),SiteCheckResultSchema=z110.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z110.object({id:SiteCheckGroupSchema,score:z110.number().int().min(0).max(100).nullable()}),SiteReportSchema=z110.object({siteUrl:z110.string(),scannedAt:z110.coerce.date(),seoScore:z110.number().int().min(0).max(100).nullable(),geoScore:z110.number().int().min(0).max(100).nullable(),groups:z110.array(SiteReportGroupSchema),checks:z110.array(SiteCheckResultSchema),blockers:z110.array(SiteCheckIdSchema).default([])}),SitePriceTierSchema=z110.enum(["budget","standard","premium","luxury"]),BusinessBriefSchema=z110.object({businessName:z110.string().trim().min(1).max(200),business:z110.string().trim().min(1).max(2e3),audience:z110.string().trim().max(1e3),competitors:z110.array(z110.string().trim().min(1).max(200)).max(10),positioning:z110.string().trim().max(2e3),priceTier:SitePriceTierSchema,homepage:z110.string().trim().max(2e3)}),SiteInterviewDraftSchema=z110.object({businessName:z110.string(),business:z110.string(),audience:z110.string(),competitors:z110.array(z110.object({name:z110.string(),url:z110.string().nullable()})).nullable(),positioning:z110.string(),priceTier:SitePriceTierSchema,homepage:z110.string()}),SiteInterviewAnswersSchema=z110.object({business:z110.object({businessName:z110.string().trim().min(1).max(200),business:z110.string().trim().min(1).max(2e3)}).optional(),competitors:z110.object({names:z110.array(z110.string().trim().min(1).max(200)).max(10)}).optional(),positioning:z110.object({positioning:z110.string().trim().max(2e3),priceTier:SitePriceTierSchema}).optional()}),SiteInterviewStepSchema=z110.enum(["business","competitors","positioning"]),SiteInterviewSchema=z110.object({status:z110.enum(["waiting","drafting","ready","failed"]),draft:SiteInterviewDraftSchema.nullable(),answers:SiteInterviewAnswersSchema}),AnswerSiteInterviewRequestSchema=z110.discriminatedUnion("step",[z110.object({step:z110.literal("business"),answer:SiteInterviewAnswersSchema.shape.business.unwrap()}),z110.object({step:z110.literal("competitors"),answer:SiteInterviewAnswersSchema.shape.competitors.unwrap()}),z110.object({step:z110.literal("positioning"),answer:SiteInterviewAnswersSchema.shape.positioning.unwrap()})]),StartSiteOnboardingRequestSchema=z110.object({organizationId:z110.string().min(1),url:z110.string().trim().min(1).max(2048),locale:z110.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema2(z110.object({projectId:z110.string()})),SiteOnboardingRefusedResponseSchema=z110.object({error:z110.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z110.object({projectId:z110.string(),siteUrl:z110.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z110.boolean(),budgetExhausted:z110.boolean(),sponsored:z110.boolean(),cloneOutOfCredits:z110.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z110.string().nullable(),competitors:z110.array(z110.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z110.coerce.date(),openedAt:z110.coerce.date().nullable(),bannerDismissed:z110.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema2(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z110.object({task:z110.enum(["scan","clone"])}),SiteOnboardingOutcomeSchema=z110.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","not_started"]),AdminSiteOnboardingsQuerySchema=z110.object({search:z110.string().trim().max(200).optional(),organizationId:z110.string().trim().min(1).max(200).optional(),startDate:z110.coerce.date().optional(),endDate:z110.coerce.date().optional(),outcomes:z110.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z110.array(SiteOnboardingOutcomeSchema).optional()),page:z110.coerce.number().int().min(1).default(1),pageSize:z110.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z110.object({projectId:z110.string(),projectName:z110.string(),organizationId:z110.string(),organizationName:z110.string().nullable(),ownerEmail:z110.string().nullable(),ownerName:z110.string().nullable(),siteUrl:z110.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z110.boolean(),cloneRetries:z110.number(),interviewAnswers:z110.number(),seoScore:z110.number().nullable(),geoScore:z110.number().nullable(),spentUsd:z110.number(),budgetCapUsd:z110.number(),capReached:z110.boolean(),cloneSeconds:z110.number().nullable(),createdAt:z110.coerce.date(),openedAt:z110.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema2(z110.object({onboardings:z110.array(AdminSiteOnboardingDTOSchema),page:z110.number(),limit:z110.number(),total:z110.number(),totalPages:z110.number()})),AdminSiteOnboardingStatsSchema=z110.object({total:z110.number(),outcomes:z110.record(SiteOnboardingOutcomeSchema,z110.number()),funnel:z110.object({started:z110.number(),business:z110.number(),competitors:z110.number(),positioning:z110.number(),opened:z110.number()}),granularity:z110.enum(["hour","day"]),series:z110.array(z110.object({at:z110.coerce.date(),outcomes:z110.record(SiteOnboardingOutcomeSchema,z110.number())})),spentUsd:z110.object({total:z110.number(),average:z110.number().nullable()}),sponsored:z110.number(),paidByOrganization:z110.object({usd:z110.number(),credits:z110.number()}),capReached:z110.number(),cloneSeconds:z110.object({median:z110.number().nullable(),average:z110.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema2(AdminSiteOnboardingStatsSchema)}});import{z as z111}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=z111.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z111.object({total:z111.number(),base:z111.number(),purchases:z111.number(),awards:z111.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z111.object({id:z111.string(),name:z111.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z111.object({type:z111.string(),brand:z111.string().nullable(),last4:z111.string().nullable(),expirationDate:z111.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z111.object({currency:z111.string(),nextPaymentAmount:z111.number().nullable(),nextPaymentAt:z111.string().nullable(),billingInterval:z111.string().nullable(),totalAmount:z111.number().nullable(),discountAmount:z111.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z111.object({id:z111.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z111.string().nullable(),currentPeriodEndsAt:z111.string().nullable(),renewsAt:z111.string().nullable(),cancelAt:z111.string().nullable(),renewAutomatically:z111.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z111.object({type:z111.enum(["low_balance","critical_balance","approaching_limit"]),message:z111.string(),estimatedPromptsRemaining:z111.number().nullable(),avgCostPerPrompt:z111.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z111.object({monthlyCredits:z111.number().nullable(),usedThisPeriod:z111.number(),remainingThisPeriod:z111.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z111.object({organizationId:z111.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z111.string().nullable(),tenureDays:z111.number().int().nonnegative(),capturedAt:z111.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z111.object({hasSubscription:z111.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z111.number().nullable(),alerts:z111.array(CreditAlertDTOSchema),portalUrl:z111.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z111.object({creditCount:z111.number().int().positive(),expiresAt:z111.string().datetime().nullable().optional(),message:z111.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z111.literal("free"),amountCents:z111.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z111.literal("purchase"),amountCents:z111.number().int().positive()}),CreditTopupRequestDTOSchema=z111.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z111.object({success:z111.boolean(),transactionId:z111.string().nullable(),newBalance:z111.number(),creditCount:z111.number(),type:z111.enum(["free","purchase"]),invoiceId:z111.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z112}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=z112.object({totalCredits:z112.number(),totalCostUsd:z112.number(),totalMessages:z112.number(),avgCostPerMessage:z112.number(),periodStart:z112.string().nullable(),periodEnd:z112.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z112.object({projectId:z112.string(),projectName:z112.string(),projectDisplayName:z112.string().nullable(),credits:z112.number(),costUsd:z112.number(),messages:z112.number(),percentage:z112.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z112.object({userId:z112.string(),userName:z112.string().nullable(),userEmail:z112.string().email().nullable(),credits:z112.number(),costUsd:z112.number(),messages:z112.number(),percentage:z112.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z112.object({date:z112.string(),credits:z112.number(),costUsd:z112.number(),messages:z112.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z112.object({userId:z112.string(),userName:z112.string().nullable(),userEmail:z112.string().email().nullable(),credits:z112.number(),costUsd:z112.number(),messages:z112.number(),percentage:z112.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z112.object({projectId:z112.string(),projectName:z112.string(),projectDisplayName:z112.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z112.array(UsageByUserForProjectDTOSchema),timeline:z112.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z112.object({summary:UsageSummaryDTOSchema,byProject:z112.array(UsageByProjectDTOSchema),byUser:z112.array(UsageByUserDTOSchema),timeline:z112.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z113}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=z113.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z113.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z113.object({startDate:z113.string().optional(),endDate:z113.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z113.coerce.number().int().positive().default(1),limit:z113.coerce.number().int().positive().max(100).default(20),sortBy:z113.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z113.string().optional(),activeOnly:z113.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z113.object({totalCredits:z113.number(),totalCostUsd:z113.number(),totalMessages:z113.number(),avgCostPerMessage:z113.number(),avgCreditsPerMessage:z113.number(),periodStart:z113.string(),periodEnd:z113.string(),creditsChange:z113.number().nullable(),costChange:z113.number().nullable(),messagesChange:z113.number().nullable(),unattributedCredits:z113.number(),unattributedCostUsd:z113.number(),unattributedMessages:z113.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z113.object({date:z113.string(),credits:z113.number(),costUsd:z113.number(),messages:z113.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z113.object({organizationId:z113.string(),organizationName:z113.string(),credits:z113.number(),costUsd:z113.number(),messages:z113.number(),percentage:z113.number(),userCount:z113.number(),projectCount:z113.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z113.object({userId:z113.string(),userName:z113.string().nullable(),userEmail:z113.string().nullable(),userImage:z113.string().nullable(),organizationId:z113.string().nullable(),organizationName:z113.string().nullable(),credits:z113.number(),costUsd:z113.number(),messages:z113.number(),percentage:z113.number(),projectCount:z113.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z113.object({projectId:z113.string(),projectName:z113.string(),projectDisplayName:z113.string().nullable(),organizationId:z113.string(),organizationName:z113.string(),credits:z113.number(),costUsd:z113.number(),messages:z113.number(),percentage:z113.number(),userCount:z113.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z113.object({id:z113.string(),name:z113.string(),value:z113.number(),percentage:z113.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z113.object({day:z113.number(),hour:z113.number(),value:z113.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z113.object({summary:UsageOverviewSummaryDTOSchema,timeline:z113.array(UsageTimelinePointDTOSchema),topOrganizations:z113.array(OrganizationUsageRowDTOSchema),topUsers:z113.array(UserUsageRowDTOSchema),topProjects:z113.array(ProjectUsageRowDTOSchema),creditDistribution:z113.array(UsageDistributionItemDTOSchema),userDistribution:z113.array(UsageDistributionItemDTOSchema),heatmap:z113.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z113.object({page:z113.number(),limit:z113.number(),totalItems:z113.number(),totalPages:z113.number(),hasMore:z113.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z113.object({organizations:z113.array(OrganizationUsageRowDTOSchema),top:z113.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z113.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z113.object({users:z113.array(ExtendedUserUsageRowDTOSchema),top:z113.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z113.string(),ownerName:z113.string().nullable(),ownerEmail:z113.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z113.object({projects:z113.array(ExtendedProjectUsageRowDTOSchema),top:z113.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z113.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z113.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z113.object({credits:z113.number(),costUsd:z113.number(),messages:z113.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z113.object({id:z113.string(),name:z113.string(),createdAt:z113.string(),memberCount:z113.number(),projectCount:z113.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z113.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z113.object({id:z113.string(),name:z113.string().nullable(),email:z113.string(),image:z113.string().nullable(),createdAt:z113.string(),organizationCount:z113.number(),projectCount:z113.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z113.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z113.object({id:z113.string(),name:z113.string(),displayName:z113.string().nullable(),createdAt:z113.string(),organizationId:z113.string(),organizationName:z113.string(),ownerId:z113.string(),ownerName:z113.string().nullable(),ownerEmail:z113.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z113.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z114}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=z114.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z114.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z114.object({command:z114.string().min(1).max(1e4),cwd:z114.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z114.record(z114.string(),z114.string()).optional(),name:z114.string().optional(),waitForCompletion:z114.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=z114.object({identifier:z114.string(),status:SandboxProcessStatusSchema,command:z114.string().optional(),startedAt:z114.string().optional(),exitCode:z114.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z114.object({processes:z114.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z114.object({processId:z114.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z114.object({success:z114.boolean(),message:z114.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z115}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z115.enum(["internal","user-visible"]),SessionSetRetentionSchema=z115.object({additionalDays:z115.number().int().min(1).max(30)}).strict()}});import{z as z116}from"zod";var PROJECT_KNOWLEDGE_MAX_CHARACTERS,ProjectKnowledgeContentSchema,ProjectKnowledgeDTOSchema,ProjectKnowledgeUpdateSchema,ProjectKnowledgeResponseSchema,ProjectKnowledgeDraftDTOSchema,ProjectKnowledgeDraftResponseSchema,ProjectKnowledgeDraftStartSchema,init_project_knowledge_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-knowledge.dto.js"(){"use strict";init_response();PROJECT_KNOWLEDGE_MAX_CHARACTERS=1e4,ProjectKnowledgeContentSchema=z116.string().refine(value=>[...value].length<=PROJECT_KNOWLEDGE_MAX_CHARACTERS&&new TextEncoder().encode(value).length<=4e4,"Knowledge must contain at most 10,000 characters and 40 KB of UTF-8 text"),ProjectKnowledgeDTOSchema=z116.object({content:ProjectKnowledgeContentSchema,updatedAt:z116.string().nullable(),updatedBy:z116.string().nullable()}),ProjectKnowledgeUpdateSchema=z116.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema2(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z116.object({id:z116.uuid(),status:z116.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z116.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema2(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z116.object({idempotencyKey:z116.uuid()})}});import{z as z117}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_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_chat_portrait();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_chat_routine_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_site_onboarding_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto();init_work_sessions();init_project_knowledge_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(`
199
199
  `).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 if(opts.defaultBranch!==void 0)branch=opts.defaultBranch,source="default";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":ctx.source==="default"?"command default":"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,defaultBranch:bootstrapOpts.defaultBranch,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
200
  `)}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
201
 
@@ -475,13 +475,13 @@ ${result.driftLines.map(l=>` ${l}`).join(`
475
475
  `).length-1;this.output.write(import_sisteransi.cursor.move(-999,t2*-1))}render(){let t2=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t2!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=j(this._prevFrame,t2),s=A(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-s),n=Math.max(0,e.numLinesBefore-s),o=e.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t2;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,o-n)),this.output.write(import_sisteransi.erase.lines(1));let a=t2.split(`
476
476
  `);this.output.write(a[o]),this._prevFrame=t2,this.output.write(import_sisteransi.cursor.move(0,a.length-o-1));return}else if(e.lines.length>1){if(i<n)o=i;else{let h=o-n;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let a=t2.split(`
477
477
  `).slice(o);this.output.write(a.join(`
478
- `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}};var Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}};var at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";var import_sisteransi2=__toESM(require_src(),1);function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}__name(Ze,"Ze");var ee=Ze();var w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z117=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
478
+ `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}};var Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}};var at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";var import_sisteransi2=__toESM(require_src(),1);function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}__name(Ze,"Ze");var ee=Ze();var w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z119=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
479
479
  `);h.push(x),f+=x.length}if(f>$2){let b=0,x=0,G2=f,M2=e-v,R2=__name((j2,D)=>et2(h,G2,j2,D,$2),"R");m?({lineCount:G2,removals:b}=R2(0,M2),G2>$2&&({lineCount:G2,removals:x}=R2(M2+1,h.length))):({lineCount:G2,removals:x}=R2(M2+1,h.length),G2>$2&&({lineCount:G2,removals:b}=R2(0,M2))),b>0&&(m=!0,h.splice(0,b)),x>0&&(g=!0,h.splice(h.length-x,x))}let C2=[];m&&C2.push(l);for(let b of h)for(let x of b)C2.push(x);return g&&C2.push(l),C2},"Y");var ot2=__name(e=>{let i=e.active??"Yes",s=e.inactive??"No";return new Q({active:i,inactive:s,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??u.withGuide,u2=`${V2(this.state)} `,n=r?`${t("gray",d2)} `:"",o=R(e.output,e.message,n,u2),c2=`${r?`${t("gray",d2)}
480
480
  `:""}${o}
481
481
  `,a=this.value?i:s;switch(this.state){case"submit":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t("dim",a)}`}case"cancel":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t(["strikethrough","dim"],a)}${r?`
482
- ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z117)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
482
+ ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z119)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
483
483
  ${t("cyan",d2)} `:`
484
- `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z117)} ${s}`}
484
+ `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z119)} ${s}`}
485
485
  ${$2}
486
486
  `}}}}).prompt()},"ot");var O2={message:__name((e=[],{symbol:i=t("gray",d2),secondarySymbol:s=t("gray",d2),output:r=process.stdout,spacing:u2=1,withGuide:n}={})=>{let o=[],c2=n??u.withGuide,a=c2?s:"",l=c2?`${i} `:"",$2=c2?`${s} `:"";for(let p2=0;p2<u2;p2++)o.push(a);let y2=Array.isArray(e)?e:e.split(`
487
487
  `);if(y2.length>0){let[p2,...m]=y2;p2.length>0?o.push(`${l}${p2}`):o.push(c2?i:"");for(let g of m)g.length>0?o.push(`${$2}${g}`):o.push(c2?s:"")}r.write(`${o.join(`
@@ -507,7 +507,7 @@ ${o}
507
507
  `}}}}).prompt(),"bt");var Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")};var re=__name((e,i)=>e.includes(`
508
508
  `)?e.split(`
509
509
  `).map(s=>i(s)).join(`
510
- `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z117)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
510
+ `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z119)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
511
511
  `:""}${n}
512
512
  `;switch(this.state){case"submit":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"selected"),c2);return`${o}${a}`}case"cancel":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"cancelled"),c2);return`${o}${a}${s?`
513
513
  ${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
@@ -522,8 +522,8 @@ ${a}${o}
522
522
  `}case"submit":{let o=n?` ${t("dim",n)}`:"",c2=i?t("gray",d2):"";return`${s}${c2}${o}`}case"cancel":{let o=n?` ${t(["strikethrough","dim"],n)}`:"",c2=i?t("gray",d2):"";return`${s}${c2}${o}${n.trim()?`
523
523
  ${c2}`:""}`}default:{let o=i?`${t("cyan",d2)} `:"",c2=i?t("cyan",E2):"";return`${s}${o}${u2}
524
524
  ${c2}
525
- `}}}}).prompt(),"Ot");init_dist();init_config();import{z as z118}from"zod";init_esm();init_config();init_sdk_transport();function createContentTransferService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch),tenantPath2=__name((projectId,route)=>`/api/tenant/${projectId}/branches/${encodeBranchPathSegment2(branch)}${route}`,"tenantPath");return{async listEntries(projectId,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return transport.request(tenantPath2(projectId,`/entries/${typeName}${query}`))},async uploadAsset(projectId,formData){return(await(await transport.response(tenantPath2(projectId,"/assets/upload"),{method:"POST",body:formData})).json()).data},async getAssetReferenceImpact(projectId,request){return(await(await transport.response(tenantPath2(projectId,"/assets/reference-impact"),{method:"POST",headers:{Accept:"application/x-ndjson","Content-Type":"application/json"},body:JSON.stringify(request)})).text()).split(`
526
- `).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))},async createForm(projectId,data){return(await transport.request(tenantPath2(projectId,"/forms"),{method:"POST",body:JSON.stringify(data)})).data},async updateForm(projectId,id,data){return(await transport.request(tenantPath2(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data)})).data}}}__name(createContentTransferService,"createContentTransferService");init_dist();function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}__name(isInteractive,"isInteractive");function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}__name(assertInteractive,"assertInteractive");init_project_context();init_project();function renderPrettyJson3(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z118.object({sourceId:z118.string().min(1),path:z118.string().min(1),name:z118.string().min(1).optional(),parentId:z118.string().min(1).optional(),folderPath:z118.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z118.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item){let filePath=path14.resolve(cwd,item.path);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=path14.basename(filePath),formData=new FormData,mimeType=path14.extname(fileName).toLowerCase()===".svg"?"image/svg+xml":void 0;return formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),item.name&&formData.append("name",item.name),item.parentId&&formData.append("parentId",item.parentId),item.folderPath&&formData.append("folderPath",item.folderPath),formData}__name(buildAssetFormData,"buildAssetFormData");function readBulkUploadManifest(cwd,manifest){let manifestPath=path14.resolve(cwd,manifest);if(!fs12.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs12.readFileSync(manifestPath,"utf8"))}catch(error){throw new Error(`Could not parse asset manifest ${manifestPath}`,{cause:error})}let result=bulkUploadManifestSchema.safeParse(parsed);if(!result.success){let issues=result.error.issues.map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw new Error(`Invalid asset manifest:
525
+ `}}}}).prompt(),"Ot");init_dist();init_config();import{z as z120}from"zod";init_esm();init_config();init_sdk_transport();function createContentTransferService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch),tenantPath2=__name((projectId,route)=>`/api/tenant/${projectId}/branches/${encodeBranchPathSegment2(branch)}${route}`,"tenantPath");return{async listEntries(projectId,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return transport.request(tenantPath2(projectId,`/entries/${typeName}${query}`))},async uploadAsset(projectId,formData){return(await(await transport.response(tenantPath2(projectId,"/assets/upload"),{method:"POST",body:formData})).json()).data},async getAssetReferenceImpact(projectId,request){return(await(await transport.response(tenantPath2(projectId,"/assets/reference-impact"),{method:"POST",headers:{Accept:"application/x-ndjson","Content-Type":"application/json"},body:JSON.stringify(request)})).text()).split(`
526
+ `).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))},async createForm(projectId,data){return(await transport.request(tenantPath2(projectId,"/forms"),{method:"POST",body:JSON.stringify(data)})).data},async updateForm(projectId,id,data){return(await transport.request(tenantPath2(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data)})).data}}}__name(createContentTransferService,"createContentTransferService");init_dist();function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}__name(isInteractive,"isInteractive");function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}__name(assertInteractive,"assertInteractive");init_project_context();init_project();function renderPrettyJson3(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z120.object({sourceId:z120.string().min(1),path:z120.string().min(1),name:z120.string().min(1).optional(),parentId:z120.string().min(1).optional(),folderPath:z120.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z120.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item){let filePath=path14.resolve(cwd,item.path);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=path14.basename(filePath),formData=new FormData,mimeType=path14.extname(fileName).toLowerCase()===".svg"?"image/svg+xml":void 0;return formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),item.name&&formData.append("name",item.name),item.parentId&&formData.append("parentId",item.parentId),item.folderPath&&formData.append("folderPath",item.folderPath),formData}__name(buildAssetFormData,"buildAssetFormData");function readBulkUploadManifest(cwd,manifest){let manifestPath=path14.resolve(cwd,manifest);if(!fs12.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs12.readFileSync(manifestPath,"utf8"))}catch(error){throw new Error(`Could not parse asset manifest ${manifestPath}`,{cause:error})}let result=bulkUploadManifestSchema.safeParse(parsed);if(!result.success){let issues=result.error.issues.map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw new Error(`Invalid asset manifest:
527
527
  ${issues.join(`
528
528
  `)}`)}return result.data}__name(readBulkUploadManifest,"readBulkUploadManifest");function parseConcurrency(value){let concurrency=Number(value);if(!Number.isInteger(concurrency)||concurrency<1||concurrency>16)throw new Error("--concurrency must be an integer between 1 and 16");return concurrency}__name(parseConcurrency,"parseConcurrency");async function mapWithConcurrency(items,concurrency,run){let results=new Array(items.length),nextIndex=0;return await Promise.all(Array.from({length:Math.min(concurrency,items.length)},async()=>{for(;nextIndex<items.length;){let index=nextIndex;nextIndex+=1,results[index]=await run(items[index])}})),results}__name(mapWithConcurrency,"mapWithConcurrency");async function assetsListCommand(options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,branch:ctx.branch});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let initialOffset=parseCursorNumber(pagination.cursor,{defaultValue:0,minimum:0}),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let offset=parseCursorNumber(cursor,{defaultValue:0,minimum:0}),response=await fimo.execute("assets.list",{projectId:ctx.projectId,branch:ctx.branch,parentId:options.parentId||void 0,search:options.search||void 0,type:options.type||void 0,mimePrefix:mimePrefix||void 0,sortBy:options.sortBy||void 0,limit:pagination.limit,offset}),hasMore=response.nextCursor!==null;return{...response,nextCursor:hasMore?String(offset+pagination.limit):null,meta:{limit:pagination.limit,offset,total:response.total,hasMore}}},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=assetPaginationTrailingArgs(options,ctx.branch);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","assets","list"],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(assetsListCommand,"assetsListCommand");function assetPaginationTrailingArgs(options,branch){let args=[];for(let[flag2,value]of[["--branch",branch],["--parent-id",options.parentId],["--search",options.search],["--type",options.type],["--mime-prefix",options.mimePrefix],["--sort-by",options.sortBy],["--cwd",options.cwd]])value!==void 0&&args.push(flag2,value);for(let[flag2,enabled]of[["--image",options.image],["--video",options.video],["--audio",options.audio]])enabled&&args.push(flag2);return args}__name(assetPaginationTrailingArgs,"assetPaginationTrailingArgs");async function assetsUploadCommand(file,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let result=await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,{path:file,name:options.name,parentId:options.parentId,folderPath:options.folderPath}));ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsBulkUploadCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),items=readBulkUploadManifest(cwd,options.file),concurrency=parseConcurrency(options.concurrency),{ctx}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let uploaded=await mapWithConcurrency(items,concurrency,async item=>{try{let asset=await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item));return{sourceId:item.sourceId,path:item.path,status:"uploaded",asset}}catch(error){return{sourceId:item.sourceId,path:item.path,status:"failed",error:error instanceof Error?error.message:String(error)}}}),failed=uploaded.filter(item=>item.status==="failed").length,result={total:uploaded.length,uploaded:uploaded.length-failed,failed,items:uploaded};ui.result({command:"assets bulk-upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")}),failed>0&&(process.exitCode=1)}__name(assetsBulkUploadCommand,"assetsBulkUploadCommand");async function assetsReadCommand(id,options,cmd){if(options.cursor!==void 0&&options.query!==void 0)throw new Error("--cursor and --query are mutually exclusive");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.read",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.read",{projectId:ctx.projectId,branch:ctx.branch,id,cursor:options.cursor,query:options.query});ui.result({command:"assets read",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsReadCommand,"assetsReadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.createFolder",{projectId:ctx.projectId,branch:ctx.branch,name,parentId:options.parentId});ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.move",{projectId:ctx.projectId,branch:ctx.branch,id,parentId:options.parentId});ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");var OTHER_BRANCHES_CAVEAT="Other Branches are not checked. This result is guidance for Current, Main, and Live, not a global unused claim.",scopeCount=__name(scope2=>scope2.referenceCount??scope2.references.length,"scopeCount");function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope2=>[scope2.scope,scopeCount(scope2)])),referenceCount=scopes.reduce((total,scope2)=>total+scopeCount(scope2),0),codeReferenceCount=scopes.reduce((total,scope2)=>total+(scope2.codeReferenceCount??0),0);return{status:scopes.some(scope2=>scope2.coverage!=="complete"||scope2.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope2=>[scope2.scope,scope2.coverage])),counts,referenceCount,codeReferenceCount,scopes,otherBranches:{checked:!1,caveat:OTHER_BRANCHES_CAVEAT}}}__name(summarizeImpact,"summarizeImpact");async function loadAssetImpact(content2,projectId,id){let events=await content2.getAssetReferenceImpact(projectId,{assetIds:[id],scopes:["current","main","live"]}),complete=events.some(event=>event.type==="complete"),scopes=events.filter(event=>event.type==="scope").map(event=>event.data);if(!complete||scopes.length!==3)throw new Error("Asset usage scan ended before Current, Main, and Live were reported");return summarizeImpact(scopes)}__name(loadAssetImpact,"loadAssetImpact");async function assetsUsageCommand(id,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await loadAssetImpact(content2,ctx.projectId,id);ui.result({command:"assets usage",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUsageCommand,"assetsUsageCommand");async function assetsReplaceCommand(id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("assets.replaceReferences",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.with}),receipt={sourceAssetId:id,replacementAssetId:options.with,scope:"current",...result,sourceRemoved:!1};ui.result({command:"assets replace",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsReplaceCommand,"assetsReplaceCommand");async function assetsRemoveCommand(id,options,cmd){if(options.permanent&&options.withoutChecking)throw new Error("--permanent cannot be combined with --without-checking");if(options.replaceWith&&options.withoutChecking)throw new Error("--replace-with and --without-checking are mutually exclusive");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);if(await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch}),options.permanent){if(options.replaceWith&&await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch}),!options.yes){assertInteractive("Pass --yes to permanently destroy the asset without a prompt.","assets remove");let confirmed=await ot2({message:options.replaceWith?`Point references everywhere at ${options.replaceWith}, then permanently destroy asset ${id} across the site? This cannot be undone.`:`Permanently destroy asset ${id} across the site? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"assets remove",message:"Cancelled."});return}}if(options.replaceWith){let replacement=await fimo.execute("assets.replaceAndDestroy",{projectId:ctx.projectId,branch:ctx.branch,id,replacementAssetId:options.replaceWith}),receipt3={assetId:id,scope:"project",permanent:!0,removed:!0,replacement:{assetId:options.replaceWith,...replacement}};ui.result({command:"assets remove",data:receipt3,render:__name(()=>renderPrettyJson3(receipt3),"render")});return}await fimo.execute("assets.destroy",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt2={assetId:id,scope:"project",permanent:!0,removed:!0};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}if(options.replaceWith){await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let outcome=await fimo.execute("assets.replaceAndRemove",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.replaceWith}),receipt2={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!1,removal:{operationId:outcome.id,expiresAt:outcome.expiresAt,undoable:outcome.undoable},replacement:{assetId:options.replaceWith,code:outcome.codeReplacement}};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}let usage,usageError;if(!options.withoutChecking)try{usage=await loadAssetImpact(content2,ctx.projectId,id)}catch(error){usageError={message:error instanceof Error?error.message:String(error)}}await fimo.execute("assets.delete",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!0,checked:!options.withoutChecking,usage,usageError};ui.result({command:"assets remove",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsRemoveCommand,"assetsRemoveCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var BRANCH_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidBranch2(branch){return typeof branch!="string"||branch.length===0||branch.length>255||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX2.test(branch)}__name(isValidBranch2,"isValidBranch");function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}__name(fnv1a82,"fnv1a8");function envResourceKey2(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(branch);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}__name(buildTenantApiUrl2,"buildTenantApiUrl");var LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.branch]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root=findProjectRoot2(options.cwd),link=root?readProjectLink(root):null;if(!root||!link)return null;let branch=currentBranch2(root);if(!branch)return null;let tenantApiUrl=buildTenantApiUrl2(link.projectId,branch,link.tenantApiBaseUrl);return{env:branch,tenantApiUrl,source:"branch",values:buildLocalRuntimeEnv({tenantApiUrl,branch}),link}}__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}__name(findStaleFimoOverride,"findStaleFimoOverride");function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}__name(staleOverrideMessage,"staleOverrideMessage");function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");function readLocalEnvFiles(cwd){let root=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root,file);if(fs13.existsSync(filePath))for(let line of fs13.readFileSync(filePath,"utf-8").split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let eq=trimmed.indexOf("=");eq<=0||(values[trimmed.slice(0,eq).trim()]=trimmed.slice(eq+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root){try{let branch=execFileSync("git",["symbolic-ref","--short","-q","HEAD"],{cwd:root,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&isValidBranch2(branch)?branch:null}catch{return null}}__name(currentBranch2,"currentBranch");function findProjectRoot2(start){let dir=path15.resolve(start);for(;;){if(fs13.existsSync(path15.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs13.existsSync(path15.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path15.dirname(dir);if(parent===dir)return null;dir=parent}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root,layout.project);if(fs13.existsSync(file))try{let parsed=JSON.parse(fs13.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}__name(readProjectLink,"readProjectLink");init_config();init_sdk_transport();init_sdk_transport();init_git();init_project_context();function buildProjectPreviewUrl(webUrl,projectId,branch){return new URL(`/app/projects/${encodeURIComponent(projectId)}/branch/${encodeURIComponent(branch)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();function branchOverride(program2){return branchOverrideFromCommand(program2)}__name(branchOverride,"branchOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),{data:branches}=await fimo.execute("branches.list",{projectId:ctx.projectId,includeDeleted:opts.verbose,includeAgentBranches:opts.all});if(branches.length===0){ui.info({command:"branch",message:"(no Branches yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:[{key:"branch",label:"BRANCH"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:branches.map(row2=>({branch:row2.branch,status:row2.status,parent:row2.parentBranch??"\u2014"})),isActive:__name(row2=>row2.branch===ctx.branch,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),parentBranch=opts.from??ctx.branch;if(isProductionBranch(name)||isProductionBranch(parentBranch)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentBranch(fimo,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let{data:created}=await fimo.execute("branches.create",{projectId:ctx.projectId,name,from:parentBranch}),createdBranch=branchNameOf(created),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),headline=`Created Branch '${createdBranch}' (status: ${created.status})`;ui.result({command:"branch",data:{headline,details:{branch:createdBranch,parent_branch:parentBranch,env:createdBranch,parent_env:parentBranch,status:created.status,studio_url:studioUrl,dashboard_url:studioUrl}},render:__name(context=>renderBranchCreated({headline,parentBranch,studioUrl},context),"render")})}__name(branchCreateCommand,"branchCreateCommand");function renderBranchCreated(result,context){let lines=[`${context.ascii?"[ok]":"\u2713"} ${result.headline}`,` Parent: ${result.parentBranch}`];return lines.push(` Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.join(`
529
529
  `)}__name(renderBranchCreated,"renderBranchCreated");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch);if(name===DEFAULT_BRANCH){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default Branch '${DEFAULT_BRANCH}'.`});return}if(isProductionBranch(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be deleted.`});return}await fimo.execute("branches.delete",{projectId:ctx.projectId,branch:name}),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{branch:name,env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),cwd=resolveProjectCwd();if(isProductionBranch(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentBranch=opts.from??ctx.branch,parentValidation=await validateParentBranch(fimo,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await fimo.execute("branches.create",{projectId:ctx.projectId,name,from:parentBranch}),created=!0}else await fimo.execute("branches.get",{projectId:ctx.projectId,branch:name});let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}let runtime=resolveLocalRuntimeEnv({cwd});ui.ok({command:"checkout",headline:`Now on Branch '${name}'`,details:{branch:name,created,git_switched:gitSwitched,parent_branch:opts.from??null,env:name,parent_env:opts.from??null,tenant_api_url:runtime?.tenantApiUrl??null},warnings:describeRuntimeWarnings(cwd,runtime)})}__name(checkoutCommand,"checkoutCommand");function describeRuntimeWarnings(cwd,runtime){if(!runtime)return["This checkout cannot derive its tenant API URL \u2014 the project link predates that. Run `fimo link` once to record it; until then the app keeps whatever runtime env values it already has."];let stale=findStaleFimoOverride({...readLocalEnvFiles(cwd),...process.env},runtime);return stale?[staleOverrideMessage(stale)]:void 0}__name(describeRuntimeWarnings,"describeRuntimeWarnings");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),{branch,conflicts}=await fimo.execute("branches.sync",{projectId:ctx.projectId,branch:ctx.branch,from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0,synced=branchNameOf(branch);ui.ok({command:"pull",headline:`Branch '${synced}' synced`,details:{branch:synced,env:synced,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentBranch(fimo,projectId,parentBranch,ctx,fromFlag){try{return await fimo.execute("branches.get",{projectId,branch:parentBranch}),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active Branch (\`${ctx.branch}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.branch}\`)`:ctx.source==="tag"?`the release tag \`${ctx.branch}\``:`the site default (\`${ctx.branch}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing Branch via \`--from <branch>\` (try \`--from ${DEFAULT_BRANCH}\`)`):ctx.source==="branch"?(fixes.push(`switch Branches first: \`fimo checkout ${DEFAULT_BRANCH}\``),fixes.push(`or pass \`--from ${DEFAULT_BRANCH}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--branch <existing>\` (try \`--branch ${DEFAULT_BRANCH}\`)`):fixes.push(`pass \`--from ${DEFAULT_BRANCH}\` to fork from main`),{ok:!1,message:`Cannot create Branch: parent Branch '${parentBranch}' doesn't exist on this site. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentBranch,"validateParentBranch");init_dist();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage site channel bindings").addHelpText("after",`
@@ -579,7 +579,7 @@ return __eta.res;
579
579
  `)}}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
580
  `).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
581
  `).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(path53){let res="";try{res=fs18.readFileSync(path53,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path53}`):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(path53){try{return JSON.parse(readFileSync4(path53,"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 z119}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=z119.object({uid:z119.string().min(1),name:z119.string().min(1).optional(),isSingleton:z119.boolean().optional(),i18n:z119.object({enabled:z119.boolean().optional()}).optional(),groups:z119.array(z119.object({id:z119.string().min(1),label:z119.string().min(1),default:z119.boolean().optional()}).strict()).optional(),fields:z119.record(z119.string(),z119.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 path53 of schemaFiles){let fileUid=basename(path53,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path53)} 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(path53,"utf-8"))}catch(error){errors.push(`${basename(path53)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path53)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path53)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path53)} 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(path53)} 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(path53)} 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:
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 z121}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=z121.object({uid:z121.string().min(1),name:z121.string().min(1).optional(),isSingleton:z121.boolean().optional(),i18n:z121.object({enabled:z121.boolean().optional()}).optional(),groups:z121.array(z121.object({id:z121.string().min(1),label:z121.string().min(1),default:z121.boolean().optional()}).strict()).optional(),fields:z121.record(z121.string(),z121.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 path53 of schemaFiles){let fileUid=basename(path53,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path53)} 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(path53,"utf-8"))}catch(error){errors.push(`${basename(path53)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path53)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path53)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path53)} 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(path53)} 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(path53)} 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
583
  - ${errors.join(`
584
584
  - `)}
585
585
  No generated files were changed.`);return schemas3}__name(loadSchemas,"loadSchemas");function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`