fimo 2.6.0 → 2.7.0-staging.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/fimo-cli/SKILL.md +1 -1
- package/assets/skills/fimo-cli/references/agents.md +1 -1
- package/assets/skills/fimo-cli/references/analytics.md +14 -0
- package/assets/skills/fimo-cli/references/content.md +2 -2
- package/assets/skills/fimo-cli/references/hosting.md +11 -0
- package/assets/skills/fimo-cli/references/locales.md +2 -2
- package/assets/skills/fimo-cli/references/pages.md +14 -2
- package/assets/skills/fimo-code/references/frameworks/astro.md +2 -0
- package/assets/skills/fimo-code/references/frameworks/next.md +12 -9
- package/assets/skills/fimo-code/references/ui.md +6 -1
- package/assets/skills/fimo-migration/SKILL.md +9 -6
- package/assets/skills/fimo-migration/references/frameworks/nextjs.md +24 -27
- package/assets/skills/fimo-migration/references/media.md +98 -62
- package/assets/skills/fimo-migration/references/qa.md +111 -11
- package/assets/skills/fimo-migration/references/workers/content-execution.md +2 -1
- package/assets/skills/fimo-migration/references/workers/validator.md +22 -6
- package/assets/skills/fimo-migration/references/workers.md +5 -3
- package/assets/skills/fimo-migration/scripts/check-rendered-guardrails.mjs +500 -0
- package/assets/skills/fimo-studio/references/agents.md +2 -0
- package/assets/skills/fimo-studio/references/publish-and-deploy.md +1 -0
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +26 -26
- package/dist/runtime/paths/get-fimo-paths.d.ts +3 -1
- package/dist/runtime/paths/get-fimo-paths.js +59 -5
- package/dist/runtime/primitives/lib/primitives.d.ts +20 -1
- package/dist/runtime/primitives/lib/primitives.js +24 -1
- package/dist/runtime/routes/index.d.ts +19 -3
- package/dist/runtime/routes/index.js +27 -2
- package/dist/scripts/validate-page-registry.js +14 -3
- package/package.json +10 -9
- package/release.json +2 -2
- package/templates/astro/package.json +2 -2
- package/templates/nextjs/package.json +3 -3
- package/templates/react-router/package.json +4 -4
- package/templates/sveltekit/package.json +2 -2
- package/templates/vite/package.json +4 -4
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 fs50=this.flowScalar(this.type);atNextItem||it2.value?(map.items.push({start,key:fs50,sep:[]}),this.onKeyLine=!0):it2.sep?this.stack.push(fs50):(Object.assign(it2,{key:fs50,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 fs50=this.flowScalar(this.type);!it2||it2.value?fc.items.push({start:[],key:fs50,sep:[]}):it2.sep?this.stack.push(fs50):Object.assign(it2,{key:fs50,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(path52,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!==void 0&&(Array.isArray(value)?value.length>0&¶ms.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path52}?${queryString}`:path52}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!==void 0&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!==void 0)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{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.isInteger(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===void 0?input.offset:decodePaginationCursor(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,sessionEnvelopeSchema,paginationShape,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;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z5.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,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(),onExpire:z5.literal("discard"),nextOperations:z5.array(z5.string())}),paginationShape={limit:z5.number().int().min(1).max(100).optional(),cursor:z5.string().min(1).optional(),offset:z5.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");__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.");return cliAgentSessionsPageSchema.parse({...page,data:page.data.map(value=>{let{env,...session}=value;return{...session,branch:session.branch??env}})})}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()})),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 project 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 project 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 project agent runs with the CLI pagination contract.",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(),page:z6.number().int().positive().optional(),limit:z6.number().int().min(1).max(200).optional()}).strict(),outputSchema:cliAgentSessionsPageSchema,buildRequest:__name(({projectId,agentName,branch,status,page,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/agents/sessions"),{agent_name:agentName,env:branch,status,page,limit})}),"buildRequest"),projectOutput:projectAgentSessionsPage}}}});import{z as z7}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsPageviewsResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body){let analytics2=analyticsPageviewsResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common();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)}),analyticsPageviewsResponseSchema=createResponseSchema(analyticsPageviewsSchema),analyticsDimensionSchema=z7.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z7.object({dimension:analyticsDimensionSchema,items:z7.array(z7.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z7.object({annotations:z7.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read site pageviews, visitors, range, breakdowns, and annotations for one Branch.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:branchNameSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,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 one ranked analytics breakdown for one Branch.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:branchNameSchema,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 Branch range.",accessScope:"read",effect:"read",inputSchema:z7.object({projectId:uuidSchema,branch:branchNameSchema,...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 project 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 project 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(),createdAt:z8.string(),updatedAt:z8.string(),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().optional(),query:z8.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=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(path52=>path52.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path52=>path52.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===void 0||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,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 project.",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 project 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 project 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:path52,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path52,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:path52})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path52})}),"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 project.",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 project.",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 project.",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 project.",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 project.",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 project.",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 project.",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,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.`).pipe(z14.string().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()}),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:path52})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path52})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe project 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 project 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:path52,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path52,content:content2,overwrite})}),"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:path52,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path52,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe project 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:path52})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path52}}),"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:z17.string().min(1).optional()}).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,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});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a project 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:z18.string().optional()}).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.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:z18.string().optional()}).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")}}}});import{z as z19}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=z19.object({key:z19.string(),value:z19.string().optional(),defaultValue:z19.string(),locale:z19.string()}),labelResponseSchema=createResponseSchema(TranslationDTOSchema),labelListOutputSchema=z19.object({data:z19.array(z19.union([TranslationDTOSchema,z19.object({key:z19.string(),values:z19.record(z19.string(),z19.string())})]))}),labelUpsertOutputSchema=z19.object({created:z19.number().int().nonnegative(),updated:z19.number().int().nonnegative(),deleted:z19.number().int().nonnegative(),defaultLocale:z19.string(),locales:z19.array(z19.string())}),labelDeleteOutputSchema=z19.object({key:z19.string(),locale:z19.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:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,key:z19.string(),value:z19.string(),locale:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,records:z19.array(z19.object({key:z19.string(),value:z19.string(),locale:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,locale:z19.string().optional(),key:z19.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 z20}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleResponseSchema,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common();projectLocaleCoverageSchema=z20.object({translated:z20.number().int().nonnegative(),total:z20.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema=createResponseSchema(z20.object({defaultLocale:z20.string(),locales:z20.array(z20.object({locale:z20.string(),isDefault:z20.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z20.string().min(1).max(40),ProjectLocaleMutationResponseSchema=createResponseSchema(z20.object({locale:z20.string()})),RemoveProjectLocaleResponseSchema=createResponseSchema(z20.object({locale:z20.string(),entriesDeleted:z20.number().int().nonnegative(),labelsDeleted:z20.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z20.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:z20.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:z20.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:z20.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 z21}from"zod";var notificationSubjectSchema,notificationViewSchema,agentQuestionSchema,projectPath2,notificationsOperations,init_notifications=__esm({"../../packages/sdk/dist/operations/notifications.js"(){"use strict";init_common();notificationSubjectSchema=z21.object({kind:z21.enum(["question","run_outcome","retained_review","merge_conflict"])}).passthrough(),notificationViewSchema=z21.object({notification:z21.object({id:uuidSchema,projectId:uuidSchema,sourceKey:z21.string(),actor:z21.object({kind:z21.enum(["user","agent","system"])}).passthrough(),payloadVersion:z21.number().int(),payload:z21.object({topic:z21.string()}).passthrough(),createdAt:z21.iso.datetime()}).passthrough(),recipient:z21.object({readAt:z21.iso.datetime().nullable(),archivedAt:z21.iso.datetime().nullable()}).passthrough(),subject:notificationSubjectSchema}),agentQuestionSchema=z21.object({id:uuidSchema,projectId:uuidSchema,threadId:uuidSchema,invocationId:uuidSchema,agentKey:z21.string(),anchorEnv:z21.string(),retainedEnv:z21.string(),state:z21.enum(["open","answered","expired","cancelled","superseded"]),request:z21.record(z21.string(),z21.unknown()),answer:z21.unknown().nullable(),askedAt:z21.iso.datetime(),expiresAt:z21.iso.datetime(),closedAt:z21.iso.datetime().nullable()}).passthrough(),projectPath2=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),notificationsOperations={"notifications.list":{domain:"notifications",summary:"List the current user\u2019s project Inbox with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z21.object({projectId:uuidSchema,topic:z21.enum(["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"]).optional(),unread:z21.boolean().optional(),archived:z21.boolean().optional(),limit:z21.number().int().min(1).max(100).optional(),cursor:z21.string().min(1).optional()}).strict(),outputSchema:z21.object({items:z21.array(notificationViewSchema),nextCursor:z21.string().nullable(),unreadCount:z21.number().int().nonnegative()}),buildRequest:__name(({projectId,topic,unread,archived,limit,cursor})=>({method:"GET",path:addQuery(projectPath2(projectId,"/notifications"),{topic,unread,archived,limit,cursor})}),"buildRequest"),projectOutput:responseData},"notifications.get":{domain:"notifications",summary:"Read one project Inbox notification.",accessScope:"read",effect:"read",inputSchema:z21.object({projectId:uuidSchema,notificationId:uuidSchema}).strict(),outputSchema:notificationViewSchema,buildRequest:__name(({projectId,notificationId})=>({method:"GET",path:projectPath2(projectId,`/notifications/${encodeURIComponent(notificationId)}`)}),"buildRequest"),projectOutput:responseData},"questions.get":{domain:"notifications",summary:"Read the decision form attached to an agent question.",accessScope:"read",effect:"read",inputSchema:z21.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:z21.object({projectId:uuidSchema,questionId:uuidSchema,answer:z21.record(z21.string(),z21.unknown())}).strict(),outputSchema:z21.object({question:agentQuestionSchema,continuationInvocationId:uuidSchema,deduped:z21.boolean()}),buildRequest:__name(({projectId,questionId,answer})=>({method:"POST",path:projectPath2(projectId,`/questions/${encodeURIComponent(questionId)}/answer`),body:answer}),"buildRequest"),projectOutput:responseData}}}});import{z as z22}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common();organizationSchema=z22.object({id:z22.string().min(1),name:z22.string(),slug:z22.string()}),organizationMemberSchema=z22.object({id:z22.string().min(1),role:z22.string(),createdAt:z22.string().optional(),user:z22.object({id:z22.string().min(1),name:z22.string().nullable().optional(),email:z22.string().nullable().optional()}).optional()}),organizationInvitationSchema=z22.object({id:z22.string().min(1),email:z22.email(),role:z22.string(),organizationId:z22.string().min(1),inviterId:z22.string().min(1),status:z22.string(),expiresAt:z22.string(),createdAt:z22.string()}).passthrough(),referralSummarySchema=z22.object({counts:z22.object({signed_up:z22.number().int(),activated:z22.number().int()}),credits:z22.object({total:z22.number().int()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z22.object({}).strict(),outputSchema:createResponseSchema(z22.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:z22.object({organizationId:z22.string().min(1)}).strict(),outputSchema:z22.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z22.object({members:z22.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z22.object({organizationId:z22.string().min(1),email:z22.email(),role:z22.enum(["owner","admin","member"]),resend:z22.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:z22.object({userId:z22.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 z23}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common();projectSchema=z23.object({id:uuidSchema,name:z23.string(),displayName:z23.string().nullable(),organizationId:z23.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z23.string().optional(),appUrl:z23.string().nullable().optional(),previewEnabled:z23.boolean().optional()}).passthrough(),projectResponseSchema=z23.object({data:projectSchema}),transferResultSchema=z23.object({projectId:z23.string(),sourceOrganizationId:z23.string(),targetOrganizationId:z23.string(),movedThreads:z23.number().int().nonnegative(),revokedInvites:z23.number().int().nonnegative(),revokedGrants:z23.number().int().nonnegative(),preservedGrants:z23.number().int().nonnegative(),warnings:z23.array(z23.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo projects the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z23.object({organizationId:z23.string().min(1).optional()}).strict(),outputSchema:z23.object({data:z23.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 project the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z23.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo project in an organization.",accessScope:"write",effect:"mutation",inputSchema:z23.object({organizationId:z23.string().min(1),displayName:z23.string().min(1).optional(),origin:z23.enum(["scratch","migration"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo project to another organization.",accessScope:"write",effect:"mutation",inputSchema:z23.object({projectId:uuidSchema,targetOrganizationId:z23.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 a user to collaborate on a Fimo project.",accessScope:"write",effect:"mutation",inputSchema:z23.object({projectId:uuidSchema,email:z23.email(),role:z23.enum(["full","edit","comment","view"])}).strict(),outputSchema:z23.object({id:z23.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z23.object({id:z23.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo project.",accessScope:"write",effect:"mutation",inputSchema:z23.object({projectId:uuidSchema}).strict(),outputSchema:z23.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z24}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,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common();dateSchema=z24.iso.datetime(),scheduleStatusSchema=z24.enum(["ok","failed"]),runStatusSchema=z24.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z24.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),secretKeys:z24.array(z24.string().min(1)),enabled:z24.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z24.string().nullable(),overPolicyReasons:z24.array(z24.string()).optional()}).passthrough(),usageSchema=z24.object({runCount:z24.number().int().nonnegative(),runsWithOutput:z24.number().int().nonnegative()}),policySchema=z24.object({maxRuns:z24.number().int().positive(),retentionDays:z24.number().int().positive().nullable(),outputRetentionDays:z24.number().int().positive(),maxOutputBytes:z24.number().int().positive()}).passthrough(),planSchema=z24.object({code:z24.enum(["Free","PAYG","Premium","Pro"]),source:z24.enum(["cached_subscription","free_fallback"]),activeSchedules:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),minCadenceMinutes:z24.number().int().positive(),maxRunMs:z24.number().int().positive(),concurrency:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),compute:z24.object({settledMs:z24.number().int().nonnegative(),activeMs:z24.number().int().nonnegative(),reservedMs:z24.number().int().nonnegative().optional(),includedMs:z24.number().int().positive(),remainingMs:z24.number().int().nonnegative(),resetsAt:dateSchema}),state:z24.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z24.array(z24.string())}).passthrough(),runSchema=z24.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z24.string().min(1),scheduleName:z24.string().min(1),command:z24.string().min(1),status:runStatusSchema,trigger:z24.enum(["cron","ui","cli"]),triggeredBy:z24.object({id:z24.string().min(1),name:z24.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z24.number().int().nullable(),errorCode:z24.string().nullable(),error:z24.string().nullable(),outputBytes:z24.number().int().nonnegative(),outputTruncated:z24.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z24.string().nullable(),secretSnapshot:z24.object({state:z24.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z24.array(z24.object({key:z24.string().min(1),updatedAt:dateSchema.nullable(),resolution:z24.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z24.object({items:z24.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z24.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z24.object({items:z24.array(runSchema),nextCursor:z24.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:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500),secretKeys:z24.array(z24.string().min(1))},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one project Branch.",accessScope:"read",effect:"read",inputSchema:z24.object({projectId:uuidSchema}).strict(),outputSchema:z24.array(scheduleSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z24.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one project Branch.",accessScope:"read",effect:"read",inputSchema:z24.object({projectId:uuidSchema}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId})=>({method:"GET",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:z24.object({projectId:uuidSchema,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId,scheduleId})=>({method:"GET",path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one project Branch.",accessScope:"agents",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,...scheduleWriteShape,enabled:z24.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,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,scheduleId,...update})=>({method:"PATCH",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:z24.object({projectId:uuidSchema,scheduleId:uuidSchema,enabled:z24.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,scheduleId,enabled})=>({method:"POST",path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a project schedule.",accessScope:"agents",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId,scheduleId})=>({method:"POST",path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one project schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z24.object({projectId:uuidSchema,scheduleId:uuidSchema,limit:z24.number().int().min(1).max(100).optional(),cursor:z24.string().min(1).optional(),status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId,scheduleId,limit,cursor,status})=>({method:"GET",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:z24.object({projectId:uuidSchema,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId,runId})=>({method:"GET",path:managementProjectPath(projectId,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one project schedule.",accessScope:"agents",effect:"mutation",inputSchema:z24.object({projectId:uuidSchema,scheduleId:uuidSchema}).strict(),outputSchema:z24.object({ok:z24.literal(!0)}),buildRequest:__name(({projectId,scheduleId})=>({method:"DELETE",path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z24.object({ok:z24.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z25}from"zod";function projectSchemaDefinition(body){return z25.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=z25.object({id:z25.string(),name:z25.string(),label:z25.string(),isSingleton:z25.boolean(),slugUnique:z25.boolean(),i18n:z25.record(z25.string(),z25.unknown()),groups:z25.array(z25.record(z25.string(),z25.unknown())),fields:z25.record(z25.string(),z25.unknown()),createdAt:z25.string(),updatedAt:z25.string()}).passthrough(),schemaListOutputSchema=z25.object({contentTypes:z25.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z25.object({typeName:z25.string().min(1).max(255),generatedPaths:z25.array(z25.string().min(1)).max(1e3),tip:z25.string().min(1)})}),schemaDefinitionInputSchema=z25.record(z25.string(),z25.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z25.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:z25.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z25.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:z25.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z25.array(schemaDefinitionInputSchema).min(1).max(100),operations:z25.array(z25.record(z25.string(),z25.unknown())).optional()}).strict(),outputSchema:z25.array(z25.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=>z25.object({data:z25.array(z25.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z25.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z25.string().min(1).max(255)}).strict(),outputSchema:z25.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z25.object({data:z25.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z25.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z25.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:z25.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z25.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z25.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:z25.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z25.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 z26}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common();environmentSchema2=z26.union([z26.literal("production"),z26.literal("preview"),uuidSchema]),secretKindSchema=z26.enum(["variable","secret"]),projectSecretSchema=z26.object({id:z26.string().min(1),projectId:z26.string().min(1),key:z26.string().min(1),kind:secretKindSchema,exposure:z26.enum(["public","private"]),environment:environmentSchema2,value:z26.string().optional(),maskedValue:z26.string().optional(),createdAt:z26.string(),updatedAt:z26.string()}),secretWriteInputSchema=z26.object({projectId:uuidSchema,key:z26.string().min(1).max(255),kind:secretKindSchema,value:z26.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one project Environment.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z26.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z26.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable or secret for one project 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 project 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 project Environment.",accessScope:"write",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,key:z26.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z26.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 project Branch.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,branch:z26.string().min(1)}).strict(),outputSchema:z26.object({branch:z26.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z26.array(z26.object({branch:z26.string().optional(),env:z26.string().optional(),parentBranch:z26.string().nullable().optional(),parentEnv:z26.string().nullable().optional(),resolvedEnvironment:z26.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 z27}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,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=z27.object({status:z27.literal("passed")}).passthrough(),sessionConflictSummarySchema=z27.object({surface:surfaceNameSchema,key:z27.string().min(1),kind:z27.string().optional(),description:z27.string(),path:z27.string().optional()}).passthrough(),surfaceDeltaItemSchema=z27.object({verb:z27.enum(["added","removed","changed","conflict"]),key:z27.string(),detail:z27.string().optional(),origin:z27.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z27.record(z27.string(),z27.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z27.object({surface:surfaceNameSchema,status:z27.enum(["ok","timed_out","failed","unchanged"]),durationMs:z27.number().int().nonnegative().optional(),changedCount:z27.number().int().nonnegative(),conflictCount:z27.number().int().nonnegative(),items:z27.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z27.boolean().optional(),error:z27.string().optional()}).passthrough(),sessionChangesSchema=z27.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z27.iso.datetime(),surfaces:z27.array(perSurfaceDeltaSchema),crossSurface:z27.array(crossSurfaceFindingSchema).optional(),fingerprint:z27.string()}).passthrough(),sessionOperationResultSchema=z27.discriminatedUnion("operation",[z27.object({operation:z27.literal("dependencies_install"),repairedInstallPolicy:z27.boolean(),tip:z27.string()}),z27.object({operation:z27.literal("schemas_sync"),tip:z27.string()})]),conflictSchema2=z27.object({surface:surfaceNameSchema,key:z27.string(),kind:z27.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z27.string(),parentValue:z27.unknown().optional(),childValue:z27.unknown().optional(),conflictingFields:z27.array(z27.string()).optional(),code:z27.object({path:z27.string(),unresolvable:z27.boolean().optional(),reason:z27.string().optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z27.object({oid:z27.string().optional(),content:z27.string().optional(),truncated:z27.boolean(),binary:z27.boolean()}),codeConflictDetailSchema=z27.object({path:z27.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z27.string(),targetTipSha:z27.string(),mergeBaseSha:z27.string().optional()}),resolutionChoiceSchema=z27.enum(["parent","child","pick"]),conflictResolutionSchema2=z27.object({surface:surfaceNameSchema,key:z27.string().min(1),choice:resolutionChoiceSchema,pickedValue:z27.unknown().optional(),fieldPicks:z27.array(z27.object({field:z27.string().min(1),choice:resolutionChoiceSchema,pickedValue:z27.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=z27.object({engine:z27.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z27.enum(["ff_only","ff_prefer","merge"]),squash:z27.boolean()}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session for a new project change.",accessScope:"code",effect:"mutation",inputSchema:z27.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z27.object({session:sessionEnvelopeSchema,adopted:z27.boolean()}),buildRequest:__name(({projectId,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:targetBranch===void 0?{}:{targetBranch}}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z27.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:"List owned work sessions for explicit lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z27.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),cursor:z27.string().min(1).optional(),limit:z27.number().int().min(1).max(100).optional()}).strict(),outputSchema:z27.object({items:z27.array(sessionEnvelopeSchema),nextCursor:z27.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z27.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z27.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.validate":{domain:"sessions",summary:"Run project validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z27.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' or 'schemas_sync'.",accessScope:"code",effect:"mutation",inputSchema:z27.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z27.string().min(1).max(100),args:z27.record(z27.string(),z27.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:z27.object({projectId:uuidSchema,sessionId:uuidSchema,action:z27.enum(["merge","discard"]),message:z27.string().max(1e3).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z27.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z27.boolean(),mergeId:uuidSchema.optional(),conflictCount:z27.number().int().nonnegative().optional(),conflicts:z27.array(sessionConflictSummarySchema).optional(),parentAdvanced:z27.boolean().optional(),code:z27.string().optional(),summary:z27.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:z27.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:z27.string().min(1).optional(),limit:z27.number().int().min(1).max(100).optional(),codePath:z27.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z27.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z27.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z27.number().int().nonnegative(),error:z27.string().nullable()}),conflicts:z27.array(conflictSchema2).max(100),nextCursor:z27.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:z27.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z27.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z27.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z27.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 z28}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:z28.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:z28.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 z29}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common();supportReportInputSchema=z29.object({message:z29.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=z29.object({id:uuidSchema,deliveryStatus:z29.enum(["pending","delivered","failed"]),message:z29.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:z29.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z30}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=z30.record(z30.string(),z30.unknown()),deliveryStatusSchema=z30.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z30.object({id:uuidSchema,projectId:uuidSchema,name:z30.string(),eventType:z30.string().min(1),enabled:z30.boolean(),destination:z30.object({host:z30.string(),maskedUrl:z30.string(),kind:z30.string()}),filter:jsonObjectSchema,headers:z30.array(jsonObjectSchema),bodyTemplate:z30.unknown().nullable(),signingEnabled:z30.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z30.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z30.string().min(1),status:deliveryStatusSchema,attemptCount:z30.number().int().nonnegative(),responseStatus:z30.number().int().nullable(),createdAt:z30.iso.datetime()}).passthrough(),attemptSchema=z30.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z30.number().int().positive(),status:z30.enum(["delivering","succeeded","failed"]),createdAt:z30.iso.datetime()}).passthrough(),deliveriesPageSchema=z30.object({items:z30.array(deliverySchema),pagination:z30.object({page:z30.number().int().positive(),limit:z30.number().int().positive(),total:z30.number().int().nonnegative(),totalPages:z30.number().int().positive(),hasMore:z30.boolean()}),stats:z30.object({total:z30.number().int().nonnegative(),succeeded:z30.number().int().nonnegative(),failed:z30.number().int().nonnegative()})}),eventSchema=z30.object({type:z30.string().min(1),family:z30.string(),description:z30.string(),variables:z30.array(z30.string()),data:z30.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one project.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema}).strict(),outputSchema:z30.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z30.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one project.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema}).strict(),outputSchema:z30.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z30.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound project webhook.",accessScope:"read",effect:"read",inputSchema:z30.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 project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z30.object({webhook:webhookSchema,signingSecret:z30.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z30.object({webhook:webhookSchema,signingSecret:z30.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.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 project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z30.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 project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z30.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z30.object({signingSecret:z30.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.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 delivery history for one project webhook using numbered pages.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema,page:z30.number().int().positive(),limit:z30.number().int().min(1).max(100)}).strict(),outputSchema:deliveriesPageSchema,buildRequest:__name(({projectId,webhookId,page,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page,limit})}),"buildRequest"),projectOutput:__name(body=>deliveriesPageSchema.parse(responseData(body)),"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z30.object({delivery:deliverySchema,attempts:z30.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z30.object({delivery:deliverySchema,attempts:z30.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z30.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 z31}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_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,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...agentsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z31.object({id:z31.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z31.string().min(1),summary:z31.string().min(1),accessScope:z31.enum(["read","write","code","agents"]),effect:z31.enum(["read","mutation"]),inputJsonSchema:z31.record(z31.string(),z31.unknown()),outputJsonSchema:z31.record(z31.string(),z31.unknown())}).strict(),fimoOperationManifestSchema=z31.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z31.toJSONSchema(operation.inputSchema,{target:"draft-7"}),outputJsonSchema:z31.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:path52,message}=issue;return`${Array.isArray(path52)&&path52.length>0?`${path52.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(path52,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path52}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path52,init={},options={}){let response=await send(path52,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",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path52,init={}){let response=await send(path52,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"} ${path52} 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,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,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,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 z32}from"zod";function filterUnknownProperties(data,schema){if(data==null)return data;if(schema instanceof z32.ZodOptional||schema instanceof z32.ZodNullable||schema instanceof z32.ZodDefault)return filterUnknownProperties(data,schema.unwrap());if(schema instanceof z32.ZodArray){if(!Array.isArray(data))return data;let itemSchema=schema.unwrap();return data.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z32.ZodDiscriminatedUnion){if(typeof data!="object"||data===null)return data;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data[discriminator],matchingSchema=unionSchema.options.find(option2=>{let discriminatorField=option2.shape[discriminator];return discriminatorField instanceof z32.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data,matchingSchema):data}if(schema instanceof z32.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 z32.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 z32.ZodObject)return createObjectDTO(schema);if(schema instanceof z32.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 z33}from"zod";function createCursorPageDataSchema(dataSchema){return z33.object({items:z33.array(dataSchema),nextCursor:z33.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z33.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema2,createPaginatedResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema2=__name(dataSchema=>z33.object({data:dataSchema}),"createResponseSchema"),createPaginatedResponseSchema=__name(dataSchema=>z33.object({data:z33.array(dataSchema),page:z33.number(),total:z33.number(),totalPages:z33.number(),hasMore:z33.boolean()}),"createPaginatedResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z34}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z34.object({page:z34.coerce.number().int().positive().default(1),limit:z34.coerce.number().int().positive().max(100).default(20)})}});import{z as z35}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:z35.coerce.date(),positiveInt:z35.number().int().positive(),nonNegativeInt:z35.number().int().nonnegative()},BaseEntitySchema=z35.object({id:z35.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z35.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z35.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z35.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z35.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z35.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z35.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z35.enum(["owner","admin","member"]),AssetTypeSchema=z35.enum(["file","folder"]),TemplateCodeSchema=z35.enum(["Free","PAYG","Premium","Pro"]),FieldTypeSchema=z35.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 z36}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=z36.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z36.object({renderId:z36.uuid(),filename:z36.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z36.url()}),AttachmentModelRenderSuccessSchema=z36.object({status:z36.literal("succeeded"),views:z36.tuple([z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z36.url()}),z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z36.url()}),z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z36.url()}),z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z36.url()})]),elapsedMs:z36.number().nonnegative(),browserElapsedMs:z36.number().nonnegative(),diagnostics:z36.unknown().optional()}),AttachmentModelRenderFailureSchema=z36.object({status:z36.literal("failed"),error:z36.literal("render_failed"),message:z36.string(),elapsedMs:z36.number().nonnegative(),browserElapsedMs:z36.number().nonnegative()}),AttachmentModelRenderResponseSchema=z36.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z36.object({browserElapsedMs:z36.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 z37}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=z37.object({cursor:z37.string().optional(),query:z37.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=z37.object({url:z37.url(),mediaType:z37.string(),filename:z37.string()}),AssetReadBaseSchema=z37.object({assetId:z37.uuid(),filename:z37.string(),mediaType:z37.string(),representation:z37.enum(["text","table","document","archive","image","transcript","video","model"]),content:z37.string(),derivedFiles:z37.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z37.literal("page"),start:z37.number().int().nonnegative(),end:z37.number().int().nonnegative(),total:z37.number().int().nonnegative(),nextCursor:z37.string().nullable(),complete:z37.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z37.literal("query"),query:z37.string(),source:z37.enum(["original-file","canonical-text","derived-files"]),truncated:z37.boolean()}),AssetReadResultSchema2=z37.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z38}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_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_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");BranchSchema=z38.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 z39}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=z39.union([z39.literal(PRODUCTION_ENVIRONMENT_KEY),z39.literal(PREVIEW_ENVIRONMENT_KEY),z39.uuid()]),CustomEnvironmentSchema=z39.object({id:z39.uuid(),projectId:z39.uuid(),name:z39.string().trim().min(1).max(64),branchPatterns:z39.array(z39.string().min(1).max(255)).min(1),description:z39.string().max(255).nullable()}),ResolvedEnvironmentSchema=z39.object({branch:BranchSchema,environment:EnvironmentKeySchema})}});import{z as z40}from"zod";var NOTIFICATION_EVENTS,NotificationAudienceSchema,NotificationEventSchema,init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env();NOTIFICATION_EVENTS={created:"notifications/created",stateChanged:"notifications/state-changed",unreadChanged:"notifications/unread-changed"},NotificationAudienceSchema=z40.object({projectId:z40.uuid(),userId:z40.string().min(1)}),NotificationEventSchema=z40.discriminatedUnion("type",[z40.object({type:z40.literal(NOTIFICATION_EVENTS.created),payload:NotificationAudienceSchema.extend({notificationId:z40.uuid()})}),z40.object({type:z40.literal(NOTIFICATION_EVENTS.stateChanged),payload:NotificationAudienceSchema.extend({notificationId:z40.uuid()})}),z40.object({type:z40.literal(NOTIFICATION_EVENTS.unreadChanged),payload:NotificationAudienceSchema})])}});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,path52){let conditionPath=[...path52,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,path52)=>{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,path52));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path52,fieldName,variant.uid]);else walk(field.schema.fields,[...path52,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path52,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path52,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_agent_provider_errors_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_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";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,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,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: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]},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)}),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_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"}),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"})})}});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[]}}function buildChatFormAnswerMetadata(block,answers,identity2={}){return ChatFormAnswerMetadataSchema.parse({...identity2,shortTitle:identity2.shortTitle??block.title,questions:block.steps.map((step,index)=>{let selectedLabels=[...answers[index]?.selectedLabels??[]],freeText=answers[index]?.freeText.trim()??"";return{header:step.header,question:step.question,answer:formatChatFormAnswer(selectedLabels,freeText,step.body.type==="capabilities"?"No capabilities approved.":void 0),selectedLabels,freeText,skipped:!1}})})}function formatChatFormAnswer(selectedLabels,freeText,emptyFallback=""){let selection=selectedLabels.join(", "),context=freeText.trim();return selection&&context?`${selection}
|
|
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(path52,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!==void 0&&(Array.isArray(value)?value.length>0&¶ms.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path52}?${queryString}`:path52}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!==void 0&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!==void 0)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{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.isInteger(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===void 0?input.offset:decodePaginationCursor(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,sessionEnvelopeSchema,paginationShape,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;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z5.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,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(),onExpire:z5.literal("discard"),nextOperations:z5.array(z5.string())}),paginationShape={limit:z5.number().int().min(1).max(100).optional(),cursor:z5.string().min(1).optional(),offset:z5.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");__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.");return cliAgentSessionsPageSchema.parse({...page,data:page.data.map(value=>{let{env,...session}=value;return{...session,branch:session.branch??env}})})}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 project 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 project 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 project agent runs with the CLI pagination contract.",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(),page:z6.number().int().positive().optional(),limit:z6.number().int().min(1).max(200).optional()}).strict(),outputSchema:cliAgentSessionsPageSchema,buildRequest:__name(({projectId,agentName,branch,status,page,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/agents/sessions"),{agent_name:agentName,env:branch,status,page,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 project 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 project 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().optional(),query:z8.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=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(path52=>path52.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path52=>path52.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===void 0||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,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 project.",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 project 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 project 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:path52,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path52,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:path52})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path52})}),"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 project.",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 project.",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 project.",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 project.",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 project.",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 project.",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 project.",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,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()}),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:path52})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path52})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe project 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 project 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:path52,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path52,content:content2,overwrite})}),"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:path52,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path52,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe project 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:path52})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path52}}),"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:z17.string().min(1).optional()}).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,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});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a project 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:z18.string().optional()}).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.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:z18.string().optional()}).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")}}}});import{z as z19}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=z19.object({key:z19.string(),value:z19.string().optional(),defaultValue:z19.string(),locale:z19.string()}),labelResponseSchema=createResponseSchema(TranslationDTOSchema),labelListOutputSchema=z19.object({data:z19.array(z19.union([TranslationDTOSchema,z19.object({key:z19.string(),values:z19.record(z19.string(),z19.string())})]))}),labelUpsertOutputSchema=z19.object({created:z19.number().int().nonnegative(),updated:z19.number().int().nonnegative(),deleted:z19.number().int().nonnegative(),defaultLocale:z19.string(),locales:z19.array(z19.string())}),labelDeleteOutputSchema=z19.object({key:z19.string(),locale:z19.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:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,key:z19.string(),value:z19.string(),locale:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,records:z19.array(z19.object({key:z19.string(),value:z19.string(),locale:z19.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:z19.object({projectId:uuidSchema,branch:branchNameSchema,locale:z19.string().optional(),key:z19.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 z20}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleResponseSchema,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common();projectLocaleCoverageSchema=z20.object({translated:z20.number().int().nonnegative(),total:z20.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema=createResponseSchema(z20.object({defaultLocale:z20.string(),locales:z20.array(z20.object({locale:z20.string(),isDefault:z20.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z20.string().min(1).max(40),ProjectLocaleMutationResponseSchema=createResponseSchema(z20.object({locale:z20.string()})),RemoveProjectLocaleResponseSchema=createResponseSchema(z20.object({locale:z20.string(),entriesDeleted:z20.number().int().nonnegative(),labelsDeleted:z20.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z20.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:z20.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:z20.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:z20.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 z21}from"zod";var notificationSubjectSchema,notificationViewSchema,agentQuestionSchema,projectPath2,notificationsOperations,init_notifications=__esm({"../../packages/sdk/dist/operations/notifications.js"(){"use strict";init_common();notificationSubjectSchema=z21.object({kind:z21.enum(["question","run_outcome","retained_review","merge_conflict","publication"])}).passthrough(),notificationViewSchema=z21.object({notification:z21.object({id:uuidSchema,projectId:uuidSchema,sourceKey:z21.string(),actor:z21.object({kind:z21.enum(["user","agent","system"])}).passthrough(),payloadVersion:z21.number().int(),payload:z21.object({topic:z21.string()}).passthrough(),createdAt:z21.iso.datetime()}).passthrough(),recipient:z21.object({readAt:z21.iso.datetime().nullable(),archivedAt:z21.iso.datetime().nullable()}).passthrough(),subject:notificationSubjectSchema}),agentQuestionSchema=z21.object({id:uuidSchema,projectId:uuidSchema,threadId:uuidSchema,invocationId:uuidSchema,agentKey:z21.string(),anchorEnv:z21.string(),retainedEnv:z21.string(),state:z21.enum(["open","answered","expired","cancelled","superseded"]),request:z21.record(z21.string(),z21.unknown()),answer:z21.unknown().nullable(),askedAt:z21.iso.datetime(),expiresAt:z21.iso.datetime(),closedAt:z21.iso.datetime().nullable()}).passthrough(),projectPath2=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),notificationsOperations={"notifications.list":{domain:"notifications",summary:"List the current user\u2019s project Inbox with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z21.object({projectId:uuidSchema,topic:z21.enum(["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"]).optional(),unread:z21.boolean().optional(),archived:z21.boolean().optional(),limit:z21.number().int().min(1).max(100).optional(),cursor:z21.string().min(1).optional()}).strict(),outputSchema:z21.object({items:z21.array(notificationViewSchema),nextCursor:z21.string().nullable(),unreadCount:z21.number().int().nonnegative()}),buildRequest:__name(({projectId,topic,unread,archived,limit,cursor})=>({method:"GET",path:addQuery(projectPath2(projectId,"/notifications"),{topic,unread,archived,limit,cursor})}),"buildRequest"),projectOutput:responseData},"notifications.get":{domain:"notifications",summary:"Read one project Inbox notification.",accessScope:"read",effect:"read",inputSchema:z21.object({projectId:uuidSchema,notificationId:uuidSchema}).strict(),outputSchema:notificationViewSchema,buildRequest:__name(({projectId,notificationId})=>({method:"GET",path:projectPath2(projectId,`/notifications/${encodeURIComponent(notificationId)}`)}),"buildRequest"),projectOutput:responseData},"questions.get":{domain:"notifications",summary:"Read the decision form attached to an agent question.",accessScope:"read",effect:"read",inputSchema:z21.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:z21.object({projectId:uuidSchema,questionId:uuidSchema,answer:z21.record(z21.string(),z21.unknown())}).strict(),outputSchema:z21.object({question:agentQuestionSchema,continuationInvocationId:uuidSchema,deduped:z21.boolean()}),buildRequest:__name(({projectId,questionId,answer})=>({method:"POST",path:projectPath2(projectId,`/questions/${encodeURIComponent(questionId)}/answer`),body:answer}),"buildRequest"),projectOutput:responseData}}}});import{z as z22}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common();organizationSchema=z22.object({id:z22.string().min(1),name:z22.string(),slug:z22.string()}),organizationMemberSchema=z22.object({id:z22.string().min(1),role:z22.string(),createdAt:z22.string().optional(),user:z22.object({id:z22.string().min(1),name:z22.string().nullable().optional(),email:z22.string().nullable().optional()}).optional()}),organizationInvitationSchema=z22.object({id:z22.string().min(1),email:z22.email(),role:z22.string(),organizationId:z22.string().min(1),inviterId:z22.string().min(1),status:z22.string(),expiresAt:z22.string(),createdAt:z22.string()}).passthrough(),referralSummarySchema=z22.object({counts:z22.object({signed_up:z22.number().int(),activated:z22.number().int()}),credits:z22.object({total:z22.number().int()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z22.object({}).strict(),outputSchema:createResponseSchema(z22.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:z22.object({organizationId:z22.string().min(1)}).strict(),outputSchema:z22.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z22.object({members:z22.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z22.object({organizationId:z22.string().min(1),email:z22.email(),role:z22.enum(["owner","admin","member"]),resend:z22.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:z22.object({userId:z22.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 z23}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common();projectSchema=z23.object({id:uuidSchema,name:z23.string(),displayName:z23.string().nullable(),organizationId:z23.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z23.string().optional(),appUrl:z23.string().nullable().optional(),previewEnabled:z23.boolean().optional()}).passthrough(),projectResponseSchema=z23.object({data:projectSchema}),transferResultSchema=z23.object({projectId:z23.string(),sourceOrganizationId:z23.string(),targetOrganizationId:z23.string(),movedThreads:z23.number().int().nonnegative(),revokedInvites:z23.number().int().nonnegative(),revokedGrants:z23.number().int().nonnegative(),preservedGrants:z23.number().int().nonnegative(),warnings:z23.array(z23.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo projects the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z23.object({organizationId:z23.string().min(1).optional()}).strict(),outputSchema:z23.object({data:z23.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 project the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z23.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo project in an organization.",accessScope:"write",effect:"mutation",inputSchema:z23.object({organizationId:z23.string().min(1),displayName:z23.string().min(1).optional(),origin:z23.enum(["scratch","migration"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo project to another organization.",accessScope:"write",effect:"mutation",inputSchema:z23.object({projectId:uuidSchema,targetOrganizationId:z23.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 a user to collaborate on a Fimo project.",accessScope:"write",effect:"mutation",inputSchema:z23.object({projectId:uuidSchema,email:z23.email(),role:z23.enum(["full","edit","comment","view"])}).strict(),outputSchema:z23.object({id:z23.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z23.object({id:z23.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo project.",accessScope:"write",effect:"mutation",inputSchema:z23.object({projectId:uuidSchema}).strict(),outputSchema:z23.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z24}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=z24.iso.datetime(),scheduleStatusSchema=z24.enum(["ok","failed"]),runStatusSchema=z24.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z24.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),secretKeys:z24.array(z24.string().min(1)),enabled:z24.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z24.string().nullable(),overPolicyReasons:z24.array(z24.string()).optional()}).passthrough(),usageSchema=z24.object({runCount:z24.number().int().nonnegative(),runsWithOutput:z24.number().int().nonnegative()}),policySchema=z24.object({maxRuns:z24.number().int().positive(),retentionDays:z24.number().int().positive().nullable(),outputRetentionDays:z24.number().int().positive(),maxOutputBytes:z24.number().int().positive()}).passthrough(),planSchema=z24.object({code:z24.enum(["Free","PAYG","Premium","Pro"]),source:z24.enum(["cached_subscription","free_fallback"]),activeSchedules:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),minCadenceMinutes:z24.number().int().positive(),maxRunMs:z24.number().int().positive(),concurrency:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),compute:z24.object({settledMs:z24.number().int().nonnegative(),activeMs:z24.number().int().nonnegative(),reservedMs:z24.number().int().nonnegative().optional(),includedMs:z24.number().int().positive(),remainingMs:z24.number().int().nonnegative(),resetsAt:dateSchema}),state:z24.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z24.array(z24.string())}).passthrough(),runSchema=z24.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z24.string().min(1),scheduleName:z24.string().min(1),command:z24.string().min(1),status:runStatusSchema,trigger:z24.enum(["cron","ui","cli"]),triggeredBy:z24.object({id:z24.string().min(1),name:z24.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z24.number().int().nullable(),errorCode:z24.string().nullable(),error:z24.string().nullable(),outputBytes:z24.number().int().nonnegative(),outputTruncated:z24.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z24.string().nullable(),secretSnapshot:z24.object({state:z24.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z24.array(z24.object({key:z24.string().min(1),updatedAt:dateSchema.nullable(),resolution:z24.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z24.object({items:z24.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z24.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z24.object({items:z24.array(runSchema),nextCursor:z24.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:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500),secretKeys:z24.array(z24.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one project Branch.",accessScope:"read",effect:"read",inputSchema:z24.object({...scheduleContextShape}).strict(),outputSchema:z24.array(scheduleSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z24.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one project Branch.",accessScope:"read",effect:"read",inputSchema:z24.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:z24.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 project Branch.",accessScope:"agents",effect:"mutation",inputSchema:z24.object({...scheduleContextShape,...scheduleWriteShape,enabled:z24.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:z24.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:z24.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z24.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 project schedule.",accessScope:"agents",effect:"mutation",inputSchema:z24.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 project schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z24.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z24.number().int().min(1).max(100).optional(),cursor:z24.string().min(1).optional(),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:z24.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 project schedule.",accessScope:"agents",effect:"mutation",inputSchema:z24.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z24.object({ok:z24.literal(!0)}),buildRequest:__name(({projectId,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z24.object({ok:z24.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z25}from"zod";function projectSchemaDefinition(body){return z25.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=z25.object({id:z25.string(),name:z25.string(),label:z25.string(),isSingleton:z25.boolean(),slugUnique:z25.boolean(),i18n:z25.record(z25.string(),z25.unknown()),groups:z25.array(z25.record(z25.string(),z25.unknown())),fields:z25.record(z25.string(),z25.unknown()),createdAt:z25.string(),updatedAt:z25.string()}).passthrough(),schemaListOutputSchema=z25.object({contentTypes:z25.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z25.object({typeName:z25.string().min(1).max(255),generatedPaths:z25.array(z25.string().min(1)).max(1e3),tip:z25.string().min(1)})}),schemaDefinitionInputSchema=z25.record(z25.string(),z25.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z25.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:z25.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z25.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:z25.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z25.array(schemaDefinitionInputSchema).min(1).max(100),operations:z25.array(z25.record(z25.string(),z25.unknown())).optional()}).strict(),outputSchema:z25.array(z25.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=>z25.object({data:z25.array(z25.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z25.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z25.string().min(1).max(255)}).strict(),outputSchema:z25.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z25.object({data:z25.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z25.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z25.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:z25.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z25.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z25.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:z25.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z25.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 z26}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common();environmentSchema2=z26.union([z26.literal("production"),z26.literal("preview"),uuidSchema]),secretKindSchema=z26.enum(["variable","secret"]),projectSecretSchema=z26.object({id:z26.string().min(1),projectId:z26.string().min(1),key:z26.string().min(1),kind:secretKindSchema,exposure:z26.enum(["public","private"]),environment:environmentSchema2,value:z26.string().optional(),maskedValue:z26.string().optional(),createdAt:z26.string(),updatedAt:z26.string()}),secretWriteInputSchema=z26.object({projectId:uuidSchema,key:z26.string().min(1).max(255),kind:secretKindSchema,value:z26.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one project Environment.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z26.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z26.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable or secret for one project 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 project 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 project Environment.",accessScope:"write",effect:"mutation",inputSchema:z26.object({projectId:uuidSchema,key:z26.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z26.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 project Branch.",accessScope:"read",effect:"read",inputSchema:z26.object({projectId:uuidSchema,branch:z26.string().min(1)}).strict(),outputSchema:z26.object({branch:z26.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z26.array(z26.object({branch:z26.string().optional(),env:z26.string().optional(),parentBranch:z26.string().nullable().optional(),parentEnv:z26.string().nullable().optional(),resolvedEnvironment:z26.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 z27}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,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=z27.object({status:z27.literal("passed")}).passthrough(),sessionConflictSummarySchema=z27.object({surface:surfaceNameSchema,key:z27.string().min(1),kind:z27.string().optional(),description:z27.string(),path:z27.string().optional()}).passthrough(),surfaceDeltaItemSchema=z27.object({verb:z27.enum(["added","removed","changed","conflict"]),key:z27.string(),detail:z27.string().optional(),origin:z27.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z27.record(z27.string(),z27.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z27.object({surface:surfaceNameSchema,status:z27.enum(["ok","timed_out","failed","unchanged"]),durationMs:z27.number().int().nonnegative().optional(),changedCount:z27.number().int().nonnegative(),conflictCount:z27.number().int().nonnegative(),items:z27.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z27.boolean().optional(),error:z27.string().optional()}).passthrough(),sessionChangesSchema=z27.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z27.iso.datetime(),surfaces:z27.array(perSurfaceDeltaSchema),crossSurface:z27.array(crossSurfaceFindingSchema).optional(),fingerprint:z27.string()}).passthrough(),sessionOperationResultSchema=z27.discriminatedUnion("operation",[z27.object({operation:z27.literal("dependencies_install"),repairedInstallPolicy:z27.boolean(),tip:z27.string()}),z27.object({operation:z27.literal("schemas_sync"),tip:z27.string()})]),conflictSchema2=z27.object({surface:surfaceNameSchema,key:z27.string(),kind:z27.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z27.string(),parentValue:z27.unknown().optional(),childValue:z27.unknown().optional(),conflictingFields:z27.array(z27.string()).optional(),code:z27.object({path:z27.string(),unresolvable:z27.boolean().optional(),reason:z27.string().optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z27.object({oid:z27.string().optional(),content:z27.string().optional(),truncated:z27.boolean(),binary:z27.boolean()}),codeConflictDetailSchema=z27.object({path:z27.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z27.string(),targetTipSha:z27.string(),mergeBaseSha:z27.string().optional()}),resolutionChoiceSchema=z27.enum(["parent","child","pick"]),conflictResolutionSchema2=z27.object({surface:surfaceNameSchema,key:z27.string().min(1),choice:resolutionChoiceSchema,pickedValue:z27.unknown().optional(),fieldPicks:z27.array(z27.object({field:z27.string().min(1),choice:resolutionChoiceSchema,pickedValue:z27.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=z27.object({engine:z27.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z27.enum(["ff_only","ff_prefer","merge"]),squash:z27.boolean()}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session for a new project change.",accessScope:"code",effect:"mutation",inputSchema:z27.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z27.object({session:sessionEnvelopeSchema,adopted:z27.boolean()}),buildRequest:__name(({projectId,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:targetBranch===void 0?{}:{targetBranch}}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z27.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:"List owned work sessions for explicit lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z27.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),cursor:z27.string().min(1).optional(),limit:z27.number().int().min(1).max(100).optional()}).strict(),outputSchema:z27.object({items:z27.array(sessionEnvelopeSchema),nextCursor:z27.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z27.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z27.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.validate":{domain:"sessions",summary:"Run project validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z27.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' or 'schemas_sync'.",accessScope:"code",effect:"mutation",inputSchema:z27.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z27.string().min(1).max(100),args:z27.record(z27.string(),z27.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:z27.object({projectId:uuidSchema,sessionId:uuidSchema,action:z27.enum(["merge","discard"]),message:z27.string().max(1e3).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z27.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z27.boolean(),mergeId:uuidSchema.optional(),conflictCount:z27.number().int().nonnegative().optional(),conflicts:z27.array(sessionConflictSummarySchema).optional(),parentAdvanced:z27.boolean().optional(),code:z27.string().optional(),summary:z27.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:z27.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:z27.string().min(1).optional(),limit:z27.number().int().min(1).max(100).optional(),codePath:z27.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z27.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z27.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z27.number().int().nonnegative(),error:z27.string().nullable()}),conflicts:z27.array(conflictSchema2).max(100),nextCursor:z27.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:z27.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z27.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z27.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z27.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 z28}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:z28.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:z28.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 z29}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common();supportReportInputSchema=z29.object({message:z29.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=z29.object({id:uuidSchema,deliveryStatus:z29.enum(["pending","delivered","failed"]),message:z29.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:z29.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z30}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=z30.record(z30.string(),z30.unknown()),deliveryStatusSchema=z30.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z30.object({id:uuidSchema,projectId:uuidSchema,name:z30.string(),eventType:z30.string().min(1),enabled:z30.boolean(),destination:z30.object({host:z30.string(),maskedUrl:z30.string(),kind:z30.string()}),filter:jsonObjectSchema,headers:z30.array(jsonObjectSchema),bodyTemplate:z30.unknown().nullable(),signingEnabled:z30.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z30.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z30.string().min(1),status:deliveryStatusSchema,attemptCount:z30.number().int().nonnegative(),responseStatus:z30.number().int().nullable(),createdAt:z30.iso.datetime()}).passthrough(),attemptSchema=z30.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z30.number().int().positive(),status:z30.enum(["delivering","succeeded","failed"]),createdAt:z30.iso.datetime()}).passthrough(),deliveriesPageSchema=z30.object({items:z30.array(deliverySchema),pagination:z30.object({page:z30.number().int().positive(),limit:z30.number().int().positive(),total:z30.number().int().nonnegative(),totalPages:z30.number().int().positive(),hasMore:z30.boolean()}),stats:z30.object({total:z30.number().int().nonnegative(),succeeded:z30.number().int().nonnegative(),failed:z30.number().int().nonnegative()})}),eventSchema=z30.object({type:z30.string().min(1),family:z30.string(),description:z30.string(),variables:z30.array(z30.string()),data:z30.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one project.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema}).strict(),outputSchema:z30.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z30.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one project.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema}).strict(),outputSchema:z30.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z30.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound project webhook.",accessScope:"read",effect:"read",inputSchema:z30.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 project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z30.object({webhook:webhookSchema,signingSecret:z30.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z30.object({webhook:webhookSchema,signingSecret:z30.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.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 project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z30.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 project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z30.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z30.object({signingSecret:z30.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one project webhook.",accessScope:"write",effect:"mutation",inputSchema:z30.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 delivery history for one project webhook using numbered pages.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema,page:z30.number().int().positive(),limit:z30.number().int().min(1).max(100)}).strict(),outputSchema:deliveriesPageSchema,buildRequest:__name(({projectId,webhookId,page,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page,limit})}),"buildRequest"),projectOutput:__name(body=>deliveriesPageSchema.parse(responseData(body)),"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z30.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z30.object({delivery:deliverySchema,attempts:z30.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z30.object({delivery:deliverySchema,attempts:z30.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z30.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 z31}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_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,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...agentsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z31.object({id:z31.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z31.string().min(1),summary:z31.string().min(1),accessScope:z31.enum(["read","write","code","agents"]),effect:z31.enum(["read","mutation"]),inputJsonSchema:z31.record(z31.string(),z31.unknown()),outputJsonSchema:z31.record(z31.string(),z31.unknown())}).strict(),fimoOperationManifestSchema=z31.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z31.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z31.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:path52,message}=issue;return`${Array.isArray(path52)&&path52.length>0?`${path52.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(path52,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path52}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path52,init={},options={}){let response=await send(path52,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",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path52,init={}){let response=await send(path52,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"} ${path52} 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,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,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 z32}from"zod";function filterUnknownProperties(data,schema){if(data==null)return data;if(schema instanceof z32.ZodOptional||schema instanceof z32.ZodNullable||schema instanceof z32.ZodDefault)return filterUnknownProperties(data,schema.unwrap());if(schema instanceof z32.ZodArray){if(!Array.isArray(data))return data;let itemSchema=schema.unwrap();return data.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z32.ZodDiscriminatedUnion){if(typeof data!="object"||data===null)return data;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data[discriminator],matchingSchema=unionSchema.options.find(option2=>{let discriminatorField=option2.shape[discriminator];return discriminatorField instanceof z32.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data,matchingSchema):data}if(schema instanceof z32.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 z32.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 z32.ZodObject)return createObjectDTO(schema);if(schema instanceof z32.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 z33}from"zod";function createCursorPageDataSchema(dataSchema){return z33.object({items:z33.array(dataSchema),nextCursor:z33.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z33.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema2,createPaginatedResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema2=__name(dataSchema=>z33.object({data:dataSchema}),"createResponseSchema"),createPaginatedResponseSchema=__name(dataSchema=>z33.object({data:z33.array(dataSchema),page:z33.number(),total:z33.number(),totalPages:z33.number(),hasMore:z33.boolean()}),"createPaginatedResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z34}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z34.object({page:z34.coerce.number().int().positive().default(1),limit:z34.coerce.number().int().positive().max(100).default(20)})}});import{z as z35}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:z35.coerce.date(),positiveInt:z35.number().int().positive(),nonNegativeInt:z35.number().int().nonnegative()},BaseEntitySchema=z35.object({id:z35.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z35.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z35.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z35.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z35.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z35.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z35.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z35.enum(["owner","admin","member"]),AssetTypeSchema=z35.enum(["file","folder"]),TemplateCodeSchema=z35.enum(["Free","PAYG","Premium","Pro"]),FieldTypeSchema=z35.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 z36}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=z36.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z36.object({renderId:z36.uuid(),filename:z36.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z36.url()}),AttachmentModelRenderSuccessSchema=z36.object({status:z36.literal("succeeded"),views:z36.tuple([z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z36.url()}),z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z36.url()}),z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z36.url()}),z36.object({angle:z36.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z36.url()})]),elapsedMs:z36.number().nonnegative(),browserElapsedMs:z36.number().nonnegative(),diagnostics:z36.unknown().optional()}),AttachmentModelRenderFailureSchema=z36.object({status:z36.literal("failed"),error:z36.literal("render_failed"),message:z36.string(),elapsedMs:z36.number().nonnegative(),browserElapsedMs:z36.number().nonnegative()}),AttachmentModelRenderResponseSchema=z36.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z36.object({browserElapsedMs:z36.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 z37}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=z37.object({cursor:z37.string().optional(),query:z37.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=z37.object({url:z37.url(),mediaType:z37.string(),filename:z37.string()}),AssetReadBaseSchema=z37.object({assetId:z37.uuid(),filename:z37.string(),mediaType:z37.string(),representation:z37.enum(["text","table","document","archive","image","transcript","video","model"]),content:z37.string(),derivedFiles:z37.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z37.literal("page"),start:z37.number().int().nonnegative(),end:z37.number().int().nonnegative(),total:z37.number().int().nonnegative(),nextCursor:z37.string().nullable(),complete:z37.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z37.literal("query"),query:z37.string(),source:z37.enum(["original-file","canonical-text","derived-files"]),truncated:z37.boolean()}),AssetReadResultSchema2=z37.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z38}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_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_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");BranchSchema=z38.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 z39}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=z39.union([z39.literal(PRODUCTION_ENVIRONMENT_KEY),z39.literal(PREVIEW_ENVIRONMENT_KEY),z39.uuid()]),CustomEnvironmentSchema=z39.object({id:z39.uuid(),projectId:z39.uuid(),name:z39.string().trim().min(1).max(64),branchPatterns:z39.array(z39.string().min(1).max(255)).min(1),description:z39.string().max(255).nullable()}),ResolvedEnvironmentSchema=z39.object({branch:BranchSchema,environment:EnvironmentKeySchema})}});import{z as z40}from"zod";var NOTIFICATION_EVENTS,NotificationAudienceSchema,NotificationEventSchema,init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env();NOTIFICATION_EVENTS={created:"notifications/created",stateChanged:"notifications/state-changed",unreadChanged:"notifications/unread-changed"},NotificationAudienceSchema=z40.object({projectId:z40.uuid(),userId:z40.string().min(1)}),NotificationEventSchema=z40.discriminatedUnion("type",[z40.object({type:z40.literal(NOTIFICATION_EVENTS.created),payload:NotificationAudienceSchema.extend({notificationId:z40.uuid()})}),z40.object({type:z40.literal(NOTIFICATION_EVENTS.stateChanged),payload:NotificationAudienceSchema.extend({notificationId:z40.uuid()})}),z40.object({type:z40.literal(NOTIFICATION_EVENTS.unreadChanged),payload:NotificationAudienceSchema})])}});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,path52){let conditionPath=[...path52,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,path52)=>{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,path52));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path52,fieldName,variant.uid]);else walk(field.schema.fields,[...path52,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path52,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path52,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_agent_provider_errors_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_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";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,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,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: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]},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)}),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_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"}),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"})})}});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[]}}function buildChatFormAnswerMetadata(block,answers,identity2={}){return ChatFormAnswerMetadataSchema.parse({...identity2,shortTitle:identity2.shortTitle??block.title,questions:block.steps.map((step,index)=>{let selectedLabels=[...answers[index]?.selectedLabels??[]],freeText=answers[index]?.freeText.trim()??"";return{header:step.header,question:step.question,answer:formatChatFormAnswer(selectedLabels,freeText,step.body.type==="capabilities"?"No capabilities approved.":void 0),selectedLabels,freeText,skipped:!1}})})}function formatChatFormAnswer(selectedLabels,freeText,emptyFallback=""){let selection=selectedLabels.join(", "),context=freeText.trim();return selection&&context?`${selection}
|
|
181
181
|
Additional context: ${context}`:selection||context||emptyFallback}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();__name(buildChatFormAnswerMetadata,"buildChatFormAnswerMetadata");ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z45.string().min(1).max(255),partial:z45.boolean().optional()});__name(formatChatFormAnswer,"formatChatFormAnswer")}});import{z as z46}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(`
|
|
182
182
|
`)}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(`
|
|
183
183
|
`)).join(`
|
|
@@ -196,8 +196,8 @@ ${block.code}
|
|
|
196
196
|
|
|
197
197
|
`)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&§ions.push(...document.details.map(reportBlockMarkdown)),sections.join(`
|
|
198
198
|
|
|
199
|
-
`)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z46.enum(REPORT_TONES),blockCommon={title:z46.string().trim().min(1).max(120).optional(),fallback:z46.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z46.object({type:z46.literal("text"),...blockCommon,text:z46.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z46.object({type:z46.literal("metric"),...blockCommon,items:z46.array(z46.object({value:z46.string().trim().min(1).max(24),unit:z46.string().trim().min(1).max(12).optional(),label:z46.string().trim().min(1).max(160),note:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z46.array(z46.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z46.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z46.object({type:z46.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z46.string().trim().min(1).max(12).optional(),points:z46.array(z46.object({label:z46.string().trim().min(1).max(24),value:z46.number().finite(),highlight:z46.boolean().optional()}).strict()).min(2).max(24),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z46.object({type:z46.literal("list"),...blockCommon,items:z46.array(z46.object({tone:ReportToneSchema.optional(),label:z46.string().trim().min(1).max(24).optional(),heading:z46.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z46.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z46.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z46.object({type:z46.literal("table"),...blockCommon,columns:z46.array(z46.object({label:z46.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z46.array(z46.object({cells:z46.array(z46.object({text:z46.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z46.object({type:z46.literal("media"),...blockCommon,assetId:z46.uuid(),alt:z46.string().trim().min(1).max(300),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z46.object({type:z46.literal("links"),...blockCommon,items:z46.array(z46.object({label:z46.string().trim().min(1).max(120),url:z46.url({protocol:/^https$/}).max(2e3),description:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z46.object({type:z46.literal("code"),...blockCommon,language:z46.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z46.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z46.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z46.object({title:z46.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z46.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z46.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z46.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(normalizeReportDocument,"normalizeReportDocument");__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z47}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z47.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z47.object({dev:z47.string().trim().min(1).optional(),build:z47.string().trim().min(1).optional(),install:z47.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z47.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z47.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z47.object({type:z47.enum(["header","cookie","query","host"]),key:z47.string().min(1).optional(),value:z47.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z47.array(FimoHostingConditionSchema).min(1).optional(),missing:z47.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),permanent:z47.boolean().optional(),statusCode:z47.union([z47.literal(301),z47.literal(302),z47.literal(307),z47.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z47.object({source:z47.string().min(1),headers:z47.array(z47.object({key:z47.string().min(1),value:z47.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z47.object({rewrites:z47.array(FimoHostingRewriteSchema).optional(),redirects:z47.array(FimoHostingRedirectSchema).optional(),headers:z47.array(FimoHostingHeaderSchema).optional(),cleanUrls:z47.boolean().optional(),trailingSlash:z47.boolean().optional()}).strict(),FimoAppConfigSchema=z47.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52){return pageRouteParamNames(path52).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z48}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,PublishUpgradeRequiredSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common2();init_env();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-6-astra","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z48.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z48.string(),displayName:z48.string().nullable(),subdomain:z48.string().nullable().optional(),subdomainUpdatedAt:z48.date().nullable().optional(),organizationId:z48.string().nullable(),createdBy:z48.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z48.boolean().default(!0),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z48.string(),thumbnailUrl:z48.string().nullable(),publishedThumbnailUrl:z48.string().nullable(),category:z48.string().nullable(),snapshotUrl:z48.string().startsWith("/").optional(),appUrl:z48.string().nullable(),lastPublishedAt:z48.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z48.object({name:z48.string().optional(),previewEnabled:z48.boolean().optional(),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z48.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z48.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z48.object({id:z48.uuid(),name:z48.string(),displayName:z48.string().nullable(),thumbnailUrl:z48.string().nullable(),category:z48.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z48.object({id:z48.string(),name:z48.string(),avatar:z48.string().nullable(),color:z48.object({bg:z48.string(),text:z48.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z48.object({path:z48.string(),content:z48.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z48.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z48.object({id:z48.string(),messageId:z48.string(),versionId:z48.string().nullable(),role:ProjectChatMessageRole,parts:z48.array(z48.any()),createdAt:z48.coerce.date()}),MessageUserMetadataSchema=z48.object({id:z48.string(),name:z48.string().nullable().optional(),image:z48.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z48.number(),metadata:z48.object({user:MessageUserMetadataSchema,changeManifest:z48.array(z48.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z48.object({versionId:z48.uuid(),commitHash:z48.string(),name:z48.string(),description:z48.string().nullable(),kind:z48.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z48.object({versionCount:z48.number().int().nonnegative(),snapshotBytes:z48.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z48.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z48.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z48.object({content:z48.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z48.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z48.object({success:z48.boolean(),message:z48.string().optional(),warning:z48.string().optional(),durationMs:z48.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z48.object({code:z48.literal("PUBLISH_UPGRADE_REQUIRED"),message:z48.string(),currentVersion:z48.number().int().positive(),targetVersion:z48.literal(4)}),ProjectPublicationStateDTOSchema=z48.object({isPublished:z48.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z48.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z48.object({label:z48.string().trim().min(1).max(120).optional(),notes:z48.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z48.object({success:z48.boolean(),message:z48.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z48.boolean(),publicationId:z48.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z49}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common2();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z49.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z49.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z49.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z49.string().nullable(),deletedAt:z49.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z49.object({id:z49.union([z49.literal(PREVIEW_ENVIRONMENT_KEY),z49.uuid()]),name:z49.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z49.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z49.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z49.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z49.object({surface:z49.enum(["code","schemas","content","translations","assets","forms"]),status:z49.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z49.number().int().nonnegative(),conflictCount:z49.number().int().nonnegative()}),BranchDiffResultSchema=z49.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z49.coerce.date(),surfaces:z49.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z50}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z50.object({projectId:z50.uuid(),name:z50.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z50.literal("production"),sourceBranch:BranchSchema,isPublished:z50.boolean(),url:z50.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PREVIEW_ENVIRONMENT_KEY),kind:z50.literal("preview"),matchedBranchCount:z50.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z50.literal("custom"),matchedBranchCount:z50.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z50.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z50.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z50.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z50.object({deletedId:z50.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z51}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z51.object({kind:z51.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z51.object({kind:z51.enum(["variable","secret"]),value:z51.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z51.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z51.object({kind:z51.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),key:z51.string(),kind:z51.literal("secret"),exposure:z51.literal("private"),environment:EnvironmentKeySchema,maskedValue:z51.string().optional(),createdAt:z51.date().transform(value=>value.toISOString()),updatedAt:z51.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z51.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z52}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z52.object({success:z52.literal(!0),downloadUrl:z52.string(),expiresAt:z52.string(),fileSize:z52.number(),duration:z52.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z52.object({success:z52.literal(!0),projectId:z52.string(),projectName:z52.string(),displayName:z52.string(),projectUrl:z52.string(),duration:z52.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z52.object({contentTypes:z52.number(),entries:z52.number(),assets:z52.number(),translations:z52.number(),forms:z52.number(),codeFiles:z52.number(),assetFiles:z52.number()}),ImportPreviewSurfaceDTOSchema=z52.object({name:z52.string(),included:z52.boolean(),count:z52.number().optional(),note:z52.string().optional()}),ImportPreviewDTOSchema=z52.object({projectName:z52.string(),displayName:z52.string().nullable(),category:z52.string().nullable(),exportedAt:z52.string(),version:z52.string(),envScope:z52.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z52.array(ImportPreviewSurfaceDTOSchema),fileSize:z52.number(),fileName:z52.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z52.object({success:z52.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z53}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z53.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z53.object({type:z53.literal("manual")}),ScheduleTriggerSchema=z53.object({type:z53.literal("schedule"),cron:z53.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z53.string().optional()}),WebhookTriggerSchema2=z53.object({type:z53.literal("webhook"),path:z53.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z53.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z54}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z54.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z54.object({token:z54.string().min(1),risk:CapabilityRiskTierSchema,description:z54.string()}),AgentSubAgentSummarySchema=z54.object({name:z54.string().min(1),grant:z54.enum(["inherit","explicit"]),effectiveCaps:z54.array(z54.string().min(1))}),AgentInstallSummaryDTOSchema=z54.object({agentName:z54.string().min(1),env:z54.string().min(1),declaredCapabilities:z54.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z54.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z54.array(CapabilitySummaryEntrySchema),criticalCapabilities:z54.array(CapabilitySummaryEntrySchema),subAgents:z54.array(AgentSubAgentSummarySchema),declaresDelegate:z54.boolean(),cycle:z54.array(z54.string()).nullable(),missingSubAgents:z54.array(z54.string()),warnings:z54.array(z54.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z55}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z55.object({kind:TriggerKindSchema,summary:z55.string()}),AgentListItemTriggerStateSchema=z55.object({triggerIndex:z55.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z55.boolean(),wired:z55.boolean(),syncError:z55.string().nullable()}),AgentListItemDTOSchema=z55.object({name:z55.string().min(1),description:z55.string().nullable(),goalFirstLine:z55.string().nullable(),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),triggers:z55.array(AgentListItemTriggerSchema),triggerStates:z55.array(AgentListItemTriggerStateSchema),paused:z55.boolean(),nextRunAt:z55.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z55.array(AgentListItemDTOSchema))}});import{z as z56}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,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=z56.object({paused:z56.boolean(),cancelledRuns:z56.number().int().nonnegative(),stopIncomplete:z56.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema),AgentDeleteResultSchema=z56.object({name:z56.string(),removedFiles:z56.number().int().positive(),commitSha:z56.string().nullable(),cancelledRuns:z56.number().int().nonnegative()}),AgentDeleteResultDTO=createDTO(AgentDeleteResultSchema),AgentDeleteResultResponseSchema=createResponseSchema2(AgentDeleteResultSchema)}});import{z as z57}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z57.object({args:z57.unknown().optional(),requestId:z57.string().min(1).max(128).optional()}),DispatchSkippedSchema=z57.object({skipped:z57.enum(["no-manual-trigger","agent-not-deployed","agent-config-invalid","manual-trigger-not-synced","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])}),DispatchAcceptedSchema=z57.object({sessionId:z57.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z57.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z58}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z58.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z58.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z58.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z58.object({verb:SurfaceDeltaVerbSchema,key:z58.string(),detail:z58.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z58.record(z58.string(),z58.unknown()).optional()}),PerSurfaceDeltaSchema=z58.object({surface:SurfaceNameSchema,status:z58.enum(["ok","timed_out","failed","unchanged"]),durationMs:z58.number().int().nonnegative().optional(),changedCount:z58.number().int().nonnegative(),conflictCount:z58.number().int().nonnegative(),items:z58.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z58.boolean().optional(),error:z58.string().optional()}),CrossSurfaceFindingSchema=z58.object({id:z58.string(),kind:z58.string(),description:z58.string(),severity:z58.enum(["warning","error"]),source:z58.object({surface:SurfaceNameSchema,key:z58.string()}),target:z58.object({surface:SurfaceNameSchema,key:z58.string()}),actions:z58.array(z58.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z58.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z58.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),agents:z58.array(z58.object({id:z58.string(),name:z58.string(),status:z58.enum(["active","paused","failed"]),lastRunAt:z58.coerce.date().nullable()})).optional(),crossSurface:z58.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z58.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),crossSurface:z58.array(CrossSurfaceFindingSchema).optional(),fingerprint:z58.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z58.object({path:z58.string(),state:z58.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z58.string(),additions:z58.number().int().nonnegative(),deletions:z58.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z58.object({oid:z58.string().optional(),content:z58.string().optional(),truncated:z58.boolean(),binary:z58.boolean()}),CodeConflictDetailSchema=z58.object({path:z58.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z58.string(),targetTipSha:z58.string(),mergeBaseSha:z58.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z58.object({id:z58.string(),slug:z58.string(),contentType:z58.string(),data:z58.record(z58.string(),z58.unknown()),updatedAt:z58.coerce.date()}),ContentRowDiffSchema=z58.object({collection:z58.string(),rowId:z58.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z58.object({name:z58.string(),label:z58.string(),isSingleton:z58.boolean(),fields:z58.record(z58.string(),z58.unknown())}),SchemaTypeDiffSchema=z58.object({typeName:z58.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z58.object({id:z58.string(),name:z58.string(),type:z58.enum(["file","folder"]),mimeType:z58.string().nullable(),storageKey:z58.string().nullable(),url:z58.string().nullable(),fileSize:z58.number().nullable(),width:z58.number().nullable(),height:z58.number().nullable(),altText:z58.string().nullable(),caption:z58.string().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),AssetDiffSchema=z58.object({assetId:z58.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z58.object({locale:z58.string(),key:z58.string(),parent:z58.string().nullable(),child:z58.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z58.object({formName:z58.string(),label:z58.string().nullable(),schemaFingerprint:z58.string(),fields:z58.record(z58.string(),z58.unknown()),settings:z58.record(z58.string(),z58.unknown()).optional()}),FormSchemaDiffSchema=z58.object({formName:z58.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema2(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z58.enum(CONFLICT_KINDS),ConflictSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),kind:ConflictKindSchema.optional(),description:z58.string(),parentValue:z58.unknown().optional(),childValue:z58.unknown().optional(),conflictingFields:z58.array(z58.string()).optional(),code:z58.object({path:z58.string(),unresolvable:z58.boolean().optional(),reason:z58.string().optional()}).optional()}),FieldPickSchema=z58.object({field:z58.string(),choice:z58.enum(["parent","child","pick","ai-pick"]),pickedValue:z58.unknown().optional(),aiSessionId:z58.string().optional()}),ConflictResolutionSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),choice:z58.enum(["parent","child","pick"]),pickedValue:z58.unknown().optional(),fieldPicks:z58.array(FieldPickSchema).optional()}),MergeResultSchema=z58.object({ok:z58.boolean(),mergeId:z58.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()})),conflicts:z58.array(ConflictSchema).optional(),summary:z58.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z58.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z58.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z58.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z58.boolean().optional()}),ResolvedStrategySchema=z58.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z58.boolean()}),MergeRequestSchema=z58.object({from:BranchSchema,allowDirectMerge:z58.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z58.object({mergeId:z58.string().uuid(),streamUrl:z58.string(),strategy:ResolvedStrategySchema,acceptedAt:z58.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z58.object({mergeId:z58.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z58.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z58.array(ConflictSchema),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedBy:z58.string().nullable(),lastEditedAt:z58.coerce.date().nullable(),initiator:z58.object({userId:z58.string().nullable(),role:z58.string().nullable(),agentName:z58.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z58.object({resolutions:z58.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z58.object({mergeId:z58.string().uuid(),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedAt:z58.coerce.date(),lastEditedBy:z58.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z58.object({mergeId:z58.string().uuid(),resolutions:z58.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z58.object({mergeId:z58.string().uuid()}),PublishReleaseRequestSchema=z58.object({version:z58.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z58.string().max(2e4).optional()}),PublishReleaseResultSchema=z58.object({releaseTag:z58.string(),sha:z58.string(),publishedAt:z58.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z59}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z59.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z59.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z59.strictObject({branch:BranchSchema.optional(),project_agents_only:z59.coerce.boolean().optional(),agent_name:z59.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z59.coerce.date().optional(),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(200).default(25),cursor:z59.coerce.date().optional()}),SessionMetricsSchema=z59.object({cpuMs:z59.number().nonnegative().default(0),netBytes:z59.number().nonnegative().default(0),walltimeMs:z59.number().nonnegative().default(0),llmTokensIn:z59.number().nonnegative().optional(),llmTokensOut:z59.number().nonnegative().optional(),stepCount:z59.number().int().nonnegative().optional(),toolCallCounts:z59.record(z59.string().min(1).max(120),z59.number().int().nonnegative()).optional(),toolCallOutcomes:z59.array(z59.object({toolName:z59.string().min(1).max(120),success:z59.boolean(),code:z59.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z59.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z59.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z59.object({capturedAt:z59.coerce.date(),fingerprint:z59.string().min(1).max(256),counts:z59.object({code:z59.number().int().nonnegative(),content:z59.number().int().nonnegative(),schemas:z59.number().int().nonnegative(),labels:z59.number().int().nonnegative(),assets:z59.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z59.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z59.object({diff:DiffReportSchema,code:z59.array(CodeFileDiffSchema.extend({raw:z59.string().max(24576)})).max(200),schemas:z59.array(SchemaTypeDiffSchema).max(200),content:z59.array(z59.object({key:z59.string().min(1).max(512),collection:z59.string().min(1).max(256),slug:z59.string().max(512).optional(),verb:z59.enum(["added","modified","deleted"]),fields:z59.array(z59.object({name:z59.string().min(1).max(256),before:z59.unknown().optional(),after:z59.unknown().optional()})).max(20)})).max(200),labels:z59.array(z59.object({key:z59.string().min(1).max(512),locale:z59.string().min(1).max(64).optional(),before:z59.unknown().nullable(),after:z59.unknown().nullable()})).max(200),assets:z59.array(z59.object({key:z59.string().min(1).max(512),name:z59.string().min(1).max(512),verb:z59.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z59.strictObject({id:z59.uuid(),projectId:z59.uuid(),branch:BranchSchema,agentName:z59.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z59.unknown().optional(),capabilities:z59.array(z59.string()).optional(),dataSources:z59.array(z59.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z59.string().nullable(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),cancelledAt:z59.coerce.date().nullable(),costUsd:z59.number().nonnegative(),costCeilingUsd:z59.number().nonnegative(),creditsUsed:z59.number().int().nonnegative().nullable(),limitCredits:z59.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),lastCheckpointId:z59.uuid().nullable(),agentBranchId:z59.uuid().nullable(),parentSessionId:z59.uuid().nullable(),terminalReason:z59.string().nullable(),errorMessage:z59.string().nullable(),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z59.string().nullable(),retainedBranch:BranchSchema.nullable().optional(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z59.object({id:z59.uuid(),sessionId:z59.uuid(),checkpointIdx:z59.number().int().nonnegative(),payloadRef:z59.string(),payloadSizeBytes:z59.number().int().nonnegative(),checksum:z59.string().length(64),createdAt:z59.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z59.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z59.object({session:AgentSessionDTOSchema,checkpoints:z59.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z59.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z59.object({reason:z59.string().min(1).max(120).optional()})}});import{z as z60}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z60.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z60.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z60.object({id:z60.uuid(),envId:z60.uuid(),sessionId:z60.uuid().nullable(),skillName:z60.string().min(1),classification:AgentBranchClassificationSchema,rationale:z60.string().nullable(),summary:z60.string().nullable(),surfaceDeltas:z60.record(z60.string(),z60.unknown()),createdAt:z60.coerce.date(),decidedAt:z60.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z60.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z60.object({path:z60.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z60.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z60.object({code:z60.literal("merge_conflict"),message:z60.string(),conflicts:z60.record(z60.string(),z60.number().int().nonnegative())})}});import{z as z61}from"zod";function agentQuestionCapabilityDecision(request,answer){let answers=answer?.answer.questions??[],decision={requested:[],approved:[],denied:[]};return request.block.steps.forEach((step,index)=>{if(step.body.type!=="capabilities")return;let answered=answers.find(item=>item.stepId===step.id)??answers[index],selected=new Set(answered?.selectedLabels??[]);for(let item of step.body.items)decision.requested.push(item),(selected.has(item.label)?decision.approved:decision.denied).push(item.token)}),decision}var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z61.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z61.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z61.object({description:z61.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z61.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z61.object({id:z61.uuid(),projectId:z61.uuid(),threadId:z61.uuid(),invocationId:z61.uuid(),agentKey:z61.string().min(1).max(120),anchorEnv:z61.string().min(1).max(64),retainedEnv:z61.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z61.string().min(1).nullable(),continuationInvocationId:z61.uuid().nullable(),askedAt:z61.coerce.date(),expiresAt:z61.coerce.date(),closedAt:z61.coerce.date().nullable()});__name(agentQuestionCapabilityDecision,"agentQuestionCapabilityDecision");AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z61.object({questionId:z61.uuid(),invocationId:z61.uuid(),askedAt:z61.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z61.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z61.object({question:AgentQuestionSchema,continuationInvocationId:z61.uuid(),deduped:z61.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z62}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z62.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z62.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z62.enum(["secret_text"]),IntegrationCredentialUsageSchema=z62.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z62.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z62.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z62.object({mode:IntegrationAuthModeSchema,label:z62.string().min(1),description:z62.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z62.object({id:z62.string().min(1),label:z62.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z62.boolean()}),IntegrationToolDefinitionDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),description:z62.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z62.object({title:z62.string().min(1),description:z62.string().min(1),command:z62.string().min(1).optional()}),IntegrationInfoDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),type:z62.enum(["native","mcp"]).optional(),url:z62.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z62.array(IntegrationAuthModeDTOSchema),credentials:z62.array(IntegrationCredentialDefinitionDTOSchema),tools:z62.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z62.enum(["available","unavailable"]).optional(),connectionCapabilities:z62.object({customIdentityCreation:z62.boolean()}).optional(),recipes:z62.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),installed:z62.boolean(),enabled:z62.boolean(),setupState:z62.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z62.string().nullable(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),connectionStatus:z62.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),installedAt:z62.coerce.date().nullable(),updatedAt:z62.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),enabled:z62.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z62.string(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z62.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z62.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z62.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z62.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z62.object({id:z62.uuid(),organizationId:z62.string().min(1),integrationKey:z62.string().min(1),registrationId:z62.uuid().nullable(),alias:z62.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z62.string().min(1),externalAccountName:z62.string().nullable(),externalBotUserId:z62.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z62.array(z62.string()),connectedAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z62.boolean(),isDefault:z62.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z62.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z62.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z62.record(McpHeaderNameSchema,z62.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z62.object({alias:z62.string().min(1).max(120).optional(),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z62.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z62.object({displayName:z62.string().trim().min(1).max(35),backgroundColor:z62.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z62.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),alias:z62.string().min(1).max(120),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}),z62.object({mode:z62.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z62.boolean().optional(),registrationId:z62.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z62.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z62.union([z62.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z62.object({type:z62.literal("mcp"),name:z62.string().trim().min(1).max(120),url:z62.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z62.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z62.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z62.object({integrationKey:z62.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z62.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("oauth"),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),ReusableMcpServerAuthKindSchema=z62.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z62.object({id:z62.uuid(),name:z62.string().min(1),host:z62.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z62.string().min(1),availability:z62.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z62.object({query:z62.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z62.object({serverId:z62.uuid()}),LinearOAuthApplicationDistributionSchema=z62.enum(["private","public"]),OrganizationLinearAppDTOSchema=z62.object({id:z62.uuid(),displayName:z62.string().min(1),description:z62.string().nullable(),iconUrl:z62.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z62.enum(["active","revoked"]),connectionIds:z62.array(z62.uuid()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z62.object({appName:z62.string().trim().min(2).max(80),description:z62.string().trim().max(1e3).optional(),iconUrl:z62.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z62.object({projectId:z62.uuid(),registrationId:z62.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z62.object({integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),integrationKey:z62.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z62.object({mode:z62.literal("oauth"),integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),BindProjectChannelRequestSchema=z62.object({ref:z62.string().min(1),connectionAlias:z62.string().min(1).optional(),agentName:z62.string().min(1).max(160).nullable().optional(),force:z62.boolean().optional()}),ListProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1)}),SearchProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1),connectionAlias:z62.string().min(1),query:z62.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),connectionId:z62.uuid(),externalWorkspaceId:z62.string().min(1),externalChannelId:z62.string().min(1),externalChannelName:z62.string().nullable(),agentName:z62.string().nullable(),enabled:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z62.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z62.object({id:z62.string().min(1),name:z62.string().min(1),visibility:z62.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z62.string().min(1).nullable(),canMove:z62.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z62.object({markdown:z62.boolean().optional(),summary:z62.boolean().optional(),links:z62.boolean().optional(),branding:z62.boolean().optional(),images:z62.boolean().optional(),html:z62.union([z62.literal("cleaned"),z62.literal("raw"),z62.boolean()]).optional(),json:z62.union([z62.boolean(),z62.object({prompt:z62.string().min(1).max(1e4),schema:z62.record(z62.string(),z62.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z62.object({url:z62.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z62.object({query:z62.string().min(1),maxResults:z62.number().int().positive().max(20).optional(),sources:z62.array(z62.enum(["web","news","images"])).min(1).max(3).optional(),categories:z62.array(z62.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z62.enum(["hour","day","week","month","year"]).optional(),location:z62.string().min(1).max(160).optional(),country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(100).optional(),types:z62.array(z62.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),sources:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),passages:z62.number().int().min(1).max(5).optional(),skills:z62.literal("only").optional(),language:z62.string().min(1).optional(),topic:z62.string().min(1).optional(),license:z62.string().min(1).optional(),minStars:z62.number().int().min(0).optional(),maxStars:z62.number().int().min(0).optional(),archived:z62.boolean().optional(),fork:z62.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(500).optional(),authors:z62.array(z62.string().min(1)).min(1).optional(),categories:z62.array(z62.string().min(1)).min(1).optional(),from:z62.iso.date().optional(),to:z62.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),query:z62.string().min(1).max(500).optional(),maxPassages:z62.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),intent:z62.string().min(1).max(500),mode:z62.enum(["similar","citers","references"]).optional(),maxResults:z62.number().int().min(1).max(500).optional(),rerank:z62.boolean().optional(),anchors:z62.array(z62.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z62.object({url:z62.string().url(),search:z62.string().min(1).optional(),limit:z62.number().int().positive().max(200).optional(),includeSubdomains:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z62.object({url:z62.string().url(),limit:z62.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z62.object({text:z62.string().min(1).max(200).optional(),cron:z62.string().min(1).max(120).optional(),timezone:z62.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z62.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z62.union([z62.object({type:z62.enum(["scrape","crawl"]).default("scrape"),urls:z62.array(z62.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z62.object({type:z62.literal("search"),queries:z62.array(z62.string().min(1).max(256)).min(1).max(12),searchWindow:z62.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z62.number().int().min(1).max(50).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z62.object({name:z62.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),notification:z62.object({email:z62.object({enabled:z62.boolean().default(!0),recipients:z62.array(z62.string().email()).min(1).max(20),includeDiffs:z62.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z62.object({monitorId:z62.string().uuid(),name:z62.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),status:z62.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z62.object({monitorId:z62.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z62.string().uuid()}),RunProjectIntegrationToolRequestSchema=z62.object({tool:z62.string().min(1),input:z62.record(z62.string(),z62.unknown()),connectionAlias:z62.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z62.object({provider:z62.string().min(1),providerCredits:z62.number().nonnegative().optional(),providerCostUsd:z62.number().nonnegative().optional(),requests:z62.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z62.object({credits:z62.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),json:z62.unknown().optional(),branding:z62.record(z62.string(),z62.unknown()).optional(),warning:z62.string().optional()}),FirecrawlSearchToolOutputSchema=z62.object({query:z62.string(),provider:z62.literal("firecrawl"),warning:z62.string().optional(),results:z62.array(z62.object({title:z62.string(),url:z62.string(),snippet:z62.string().optional(),content:z62.string().optional(),score:z62.number().optional(),publishedAt:z62.string().optional()}))}),FirecrawlResearchPaperSchema=z62.object({paperId:z62.string(),primaryId:z62.string().optional(),ids:z62.record(z62.string(),z62.array(z62.string())).optional(),title:z62.string().optional(),abstract:z62.string().optional(),score:z62.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z62.object({text:z62.string(),score:z62.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(z62.object({id:z62.string(),type:z62.string().min(1).optional(),url:z62.string(),title:z62.string().optional(),passages:z62.array(z62.object({text:z62.string()}).passthrough())}).passthrough()),coverage:z62.record(z62.string(),z62.string()).optional(),reranked:z62.boolean().optional(),repos:z62.array(z62.record(z62.string(),z62.unknown())).optional(),sources:z62.array(z62.record(z62.string(),z62.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),paper:z62.record(z62.string(),z62.unknown()),paperId:z62.string().optional(),query:z62.string().optional(),passages:z62.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema),poolSize:z62.number().int().nonnegative(),truncated:z62.boolean(),note:z62.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),count:z62.number(),links:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),description:z62.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),total:z62.number(),pages:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),warning:z62.string().optional()})),warning:z62.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z62.object({cron:z62.string().optional(),text:z62.string().optional(),timezone:z62.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z62.object({id:z62.string().optional(),type:z62.enum(["scrape","crawl","search"]).optional(),urls:z62.array(z62.string()).optional(),queries:z62.array(z62.string()).optional(),searchWindow:z62.string().optional(),maxResults:z62.number().optional(),includeDomains:z62.array(z62.string()).optional(),excludeDomains:z62.array(z62.string()).optional(),scrapeOptions:z62.record(z62.string(),z62.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z62.object({id:z62.string(),name:z62.string(),status:z62.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z62.string().nullable().optional(),lastRunAt:z62.string().nullable().optional(),currentCheckId:z62.string().nullable().optional(),targets:z62.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z62.string().nullable().optional(),judgeEnabled:z62.boolean().optional(),estimatedCreditsPerMonth:z62.number().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z62.object({id:z62.string(),monitorId:z62.string(),scheduledFor:z62.string().nullable().optional(),startedAt:z62.string().nullable().optional(),finishedAt:z62.string().nullable().optional(),estimatedCredits:z62.number().nullable().optional(),reservedCredits:z62.number().nullable().optional(),actualCredits:z62.number().nullable().optional(),billingStatus:z62.string().nullable().optional(),summary:z62.object({totalPages:z62.number().optional(),same:z62.number().optional(),changed:z62.number().optional(),new:z62.number().optional(),removed:z62.number().optional(),error:z62.number().optional()}).passthrough().optional(),error:z62.string().nullable().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitors:z62.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),deleted:z62.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),checks:z62.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),check:FirecrawlMonitorCheckOutputSchema,next:z62.string().optional()}),FirecrawlToolKeySchema=z62.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z62.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),tool:z62.string().min(1),connectionAlias:z62.string().min(1).nullable().optional(),output:z62.record(z62.string(),z62.unknown()),executedAt:z62.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z62.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z62.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z62.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z62.array(ProjectChannelCandidateDTOSchema))}});import{z as z63}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z63.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z63.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z63.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z63.object({userId:z63.string().min(1),name:z63.string(),email:z63.string().min(1),subscribed:z63.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z63.object({maxSubscribers:z63.number().int().positive(),subscriberCount:z63.number().int().nonnegative(),effectiveRecipientCount:z63.number().int().nonnegative(),currentUserSubscribed:z63.boolean(),candidates:z63.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z63.object({userIds:z63.array(z63.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z63.object({topic:UserManagedNotificationTopicSchema,enabled:z63.boolean(),source:z63.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z63.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z63.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z63.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z63.string().nullable(),maskedEmail:z63.string().min(1),applied:z63.boolean(),expiresAt:z63.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z63.object({scheduleId:z63.string().min(1),scheduleName:z63.string(),projectId:z63.string().min(1),projectName:z63.string(),env:z63.string().min(1)}),FollowedSchedulesSchema=z63.object({schedules:z63.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z64}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common2();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z64.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z64.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z64.uuid(),env:z64.string().min(1),name:z64.string().min(1),cron:z64.string().min(1),command:z64.string().min(1),secretKeys:z64.array(z64.string().min(1)),enabled:z64.boolean(),lastRunAt:z64.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z64.string().nullable(),suspendedAt:z64.coerce.date().nullable().optional(),suspensionReason:z64.string().nullable().optional(),overPolicyReasons:z64.array(z64.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120),cron:z64.string().min(1).max(120),command:z64.string().min(1).max(500),secretKeys:z64.array(ProjectSecretKeySchema).default([]),enabled:z64.boolean().optional()}),UpdateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120).optional(),cron:z64.string().min(1).max(120).optional(),command:z64.string().min(1).max(500).optional(),secretKeys:z64.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z64.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z64.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z64.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z64.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z64.object({maxRuns:z64.number().int().positive(),retentionDays:z64.number().int().positive().nullable(),outputRetentionDays:z64.number().int().positive(),maxOutputBytes:z64.number().int().positive()}),SchedulePolicyStateSchema=z64.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z64.object({code:z64.enum(["Free","PAYG","Premium","Pro"]),source:z64.enum(["cached_subscription","free_fallback"]),activeSchedules:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().nonnegative()}),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),concurrency:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().positive()}),compute:z64.object({settledMs:z64.number().int().nonnegative(),activeMs:z64.number().int().nonnegative(),reservedMs:z64.number().int().nonnegative().optional(),includedMs:z64.number().int().nonnegative(),remainingMs:z64.number().int().nonnegative(),resetsAt:z64.coerce.date()}),upgrade:z64.object({code:z64.literal("Pro"),activeSchedulesLimit:z64.number().int().positive(),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),maxConcurrentRuns:z64.number().int().positive(),computeIncludedMs:z64.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z64.array(z64.string())}),ProjectScheduleUsageSchema=z64.object({runCount:z64.number().int().nonnegative(),runsWithOutput:z64.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z64.object({id:z64.uuid(),scheduleId:z64.uuid(),projectId:z64.uuid(),env:z64.string().min(1),scheduleName:z64.string().min(1),command:z64.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z64.object({id:z64.string().min(1),name:z64.string().min(1)}).nullable(),queuedAt:z64.coerce.date(),startedAt:z64.coerce.date().nullable(),finishedAt:z64.coerce.date().nullable(),exitCode:z64.number().int().nullable(),errorCode:z64.string().nullable(),error:z64.string().nullable(),outputBytes:z64.number().int().nonnegative(),outputTruncated:z64.boolean(),outputExpiresAt:z64.coerce.date().nullable(),metadataExpiresAt:z64.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z64.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z64.coerce.date().nullable(),items:z64.array(z64.object({key:z64.string().min(1),updatedAt:z64.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z64.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z64.object({trigger:z64.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z64.object({limit:z64.coerce.number().int().min(1).max(100).default(25),cursor:z64.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z64.object({items:z64.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z64.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z64.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z64.object({items:z64.array(ProjectScheduleRunDTOSchema),nextCursor:z64.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z65}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z65.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z65.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z65.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z65.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("user"),userId:z65.string().min(1)}).strict(),z65.object({kind:z65.literal("agent"),agentKey:z65.string().min(1).max(120),agentId:z65.uuid().optional()}).strict(),z65.object({kind:z65.literal("system")}).strict()]),NotificationSummarySchema=z65.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z65.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z65.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z65.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z65.discriminatedUnion("topic",[z65.object({topic:z65.literal("agent_question"),questionId:z65.uuid(),title:z65.string().trim().min(1).max(80),description:z65.string().trim().min(1).max(240)}).strict(),z65.object({topic:z65.literal("agent_run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().optional(),proposalId:z65.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z65.object({id:z65.uuid(),projectId:z65.uuid(),sourceKey:z65.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z65.literal(1),payload:NotificationPayloadSchema,createdAt:z65.coerce.date()}),NotificationRecipientStateSchema=z65.object({id:z65.uuid(),notificationId:z65.uuid(),projectId:z65.uuid(),userId:z65.string().min(1),readAt:z65.coerce.date().nullable(),archivedAt:z65.coerce.date().nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationDeliveryStateSchema=z65.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z65.object({id:z65.uuid(),notificationRecipientId:z65.uuid(),projectId:z65.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z65.number().int().nonnegative(),nextAttemptAt:z65.coerce.date().nullable(),lastAttemptAt:z65.coerce.date().nullable(),sentAt:z65.coerce.date().nullable(),failureCode:z65.string().max(80).nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationPreferenceSchema=z65.object({topic:WorkNotificationTopicSchema,channel:z65.literal("email"),enabled:z65.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z65.enum(["default","explicit"])}),NotificationSubjectSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("question"),questionId:z65.uuid()}).strict(),z65.object({kind:z65.literal("run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z65.object({kind:z65.literal("retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().nullable(),proposalId:z65.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z65.object({kind:z65.literal("merge_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().nullable()}).strict()]),NotificationViewSchema=z65.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema2(NotificationViewSchema),NotificationListSchema=z65.object({items:z65.array(NotificationViewSchema),nextCursor:z65.string().nullable(),unreadCount:z65.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema2(NotificationListSchema),ListNotificationsQuerySchema=z65.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z65.string().min(1).max(120).optional(),sourceKey:z65.string().min(1).max(255).optional(),unread:z65.stringbool().optional(),archived:z65.stringbool().optional(),limit:z65.coerce.number().int().min(1).max(100).optional(),cursor:z65.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z65.object({recipient:NotificationRecipientStateSchema,unreadCount:z65.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema2(NotificationStateSchema),UpdateNotificationStateRequestSchema=z65.object({read:z65.boolean().optional(),archived:z65.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived."),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z65.object({enabled:z65.boolean(),pausedUntil:z65.coerce.date().nullable(),source:z65.enum(["default","explicit"]).optional()})}});import{z as z66}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,QUESTION_DIGEST_PREFERENCE_ENTRY_ID,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z66.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_question","work_review.agent_conflict","schedule.schedule_health","schedule.schedule_compute_allowance","usage.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z66.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z66.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z66.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z66.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z66.object({enabled:z66.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z66.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z66.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z66.enum(["work_review","schedule","usage"]),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z66.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),id:z66.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z66.literal("question_digest"),enabled:z66.boolean(),source:PreferenceSourceSchema,pausedUntil:z66.coerce.date().nullable()}).strict(),z66.object({kind:z66.literal("provider_subscription"),id:z66.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z66.literal("marketing"),name:z66.string(),description:z66.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z66.object({email:EmailNotificationPreferenceSchema,entries:z66.array(NotificationPreferenceEntrySchema),unavailableGroups:z66.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z66.object({enabled:z66.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),enabled:z66.boolean()}).strict(),z66.object({kind:z66.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),enabled:z66.boolean(),pauseDays:z66.number().int().min(1).max(MAX_QUESTION_DIGEST_PAUSE_DAYS).nullable().optional()}).strict().refine(body=>body.enabled||!body.pauseDays,"Pausing requires the toggle to be enabled."),z66.object({kind:z66.literal("provider_subscription"),enabled:z66.boolean()}).strict()])}});import{z as z67}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z67.object({surface:SurfaceNameSchema,key:z67.string(),label:z67.string()}),InlineSchema=z67.object({text:z67.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z67.discriminatedUnion("type",[z67.object({type:z67.literal("paragraph"),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("preview"),ref:DiffRefSchema,caption:z67.string().optional()}),z67.object({type:z67.literal("code"),code:z67.string(),lang:z67.string().optional(),caption:z67.string().optional()}),z67.object({type:z67.literal("risk"),level:z67.enum(["warning","error"]),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("list"),items:z67.array(z67.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z67.object({headline:z67.string(),blocks:z67.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z67.object({summary:EnvDiffSummarySchema,fingerprint:z67.string(),generatedAt:z67.coerce.date(),cached:z67.boolean().optional(),credits:z67.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z68}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z68.object({date:z68.string(),visitors:z68.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z68.object({key:z68.string(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z68.object({path:z68.string(),pageName:z68.string().nullable().optional(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z68.object({preset:z68.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z68.string(),requestedTo:z68.string(),effectiveFrom:z68.string(),effectiveTo:z68.string(),isRetentionLimited:z68.boolean(),groupBy:z68.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z68.object({date:z68.string(),content:z68.string(),updatedAt:z68.string(),updatedByUserId:z68.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z68.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z68.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative(),botPageviews:z68.number().int().nonnegative(),botVisitors:z68.number().int().nonnegative(),bounceRate:z68.number().min(0).max(100),viewsPerVisit:z68.number().nonnegative(),averageVisitDurationSeconds:z68.number().nonnegative(),visitorsSeries:z68.array(ProjectDailyVisitorsDTOSchema),topPages:z68.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z68.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z69}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common2();init_create_dto();ProjectInviteDTOSchema=z69.object({id:z69.string(),email:z69.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z69.coerce.date(),createdAt:z69.coerce.date(),inviterUserId:z69.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z69.object({id:z69.string(),token:z69.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z69.object({success:z69.boolean(),projectId:z69.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z70}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z70.object({id:z70.string(),name:z70.string(),image:z70.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z70.object({count:z70.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z70.object({counts:z70.object({signed_up:z70.int(),activated:z70.int()}),credits:z70.object({total:z70.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z70.email(),emailVerified:z70.boolean(),createdAt:z70.coerce.date(),updatedAt:z70.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z71}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common2();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z71.object({id:z71.string(),principalType:ProjectPrincipalTypeSchema,principalId:z71.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z71.coerce.date(),expiresAt:z71.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z71.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z71.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z71.record(z71.string(),z71.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z71.object({access:z71.array(ProjectAccessItemDTOSchema),invites:z71.array(ProjectInviteDTOSchema),organization:z71.object({name:z71.string().nullable(),logo:z71.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z71.object({success:z71.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z71.object({success:z71.boolean(),projectId:z71.uuid()}))}});import{z as z72}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common2();init_create_dto();PublicationStateDTOSchema=z72.object({publicationStatus:PublicationStatusSchema,appUrl:z72.string().nullable(),lastPublishedAt:z72.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z73}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z73.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z73.object({branch:BranchSchema,revision:z73.string().min(1).max(64).nullable(),generation:z73.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z73.url().nullable()})}});import{z as z74}from"zod";var 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=z74.object({code:z74.literal("PREVIEW_UPGRADE_REQUIRED"),message:z74.string(),currentVersion:z74.number().int().positive(),targetVersion:z74.literal(4)}),PreviewBridgePackageSchema=z74.object({name:z74.string().min(1),version:z74.string().min(1)}),PreviewBridgeCapabilitySchema=z74.object({integrated:z74.boolean(),packages:z74.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z74.object({url:z74.url(),expiresAt:z74.iso.datetime().nullable(),source:z74.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z74.object({name:z74.string().min(1),locator:z74.string().min(1).optional(),source:z74.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z74.object({kind:z74.literal("dependency_build_scripts_blocked"),packageManager:z74.enum(["pnpm","yarn","bun"]),packages:z74.array(z74.string()),targets:z74.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z74.string(),approvalKey:z74.string(),command:z74.string().optional(),approval:z74.object({id:z74.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z74.object({code:z74.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z74.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z74.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z74.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z74.object({message:z74.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z74.number().int().optional().catch(void 0),logTail:z74.array(z74.string()).optional().catch(void 0),logTailTruncated:z74.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z74.object({approvalId:z74.uuid()}),PreviewInstallPolicyApprovalEventSchema=z74.discriminatedUnion("type",[z74.object({type:z74.literal("progress"),step:z74.enum(["approval","install","restart","readiness"]),message:z74.string()}),z74.object({type:z74.literal("approved")}),z74.object({type:z74.literal("complete")}),z74.object({type:z74.literal("error"),code:z74.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z74.string()})])}});import{z as z75}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common2();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z75.string(),slug:z75.string().nullable(),logo:z75.string().nullable(),metadata:z75.record(z75.string(),z75.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z75.object({id:z75.string(),name:z75.string(),email:z75.email(),image:z75.string().nullable()}),OrganizationMemberDTOSchema=z75.object({id:z75.string(),userId:z75.string(),organizationId:z75.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z75.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z76}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,AutomaticSpendStopDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,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=z76.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z76.object({reason:CancellationReasonCodeSchema,details:z76.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z76.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z76.object({offerVersion:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),renewsOn:z76.string()}),PlanMigrationPreviewDTOSchema=z76.object({currency:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),startsAt:z76.string(),renewsAt:z76.string(),nextRenewalAmount:z76.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z76.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z76.object({id:z76.string(),organizationId:z76.string(),legacySubscriptionId:z76.string(),offeredPlanCode:z76.string(),offeredPlanName:z76.string(),offeredPriceAmount:z76.number(),offeredCurrency:z76.string(),offerVersion:z76.string(),state:PlanMigrationStateSchema,checkoutToken:z76.string().nullable(),deadlineAt:z76.string(),transitions:z76.array(z76.object({event:z76.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z76.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z76.object({included:z76.number().optional(),unitPrice:z76.number().optional(),dailyCap:z76.number().nullable().optional()}),EntitlementsDTOSchema=z76.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z76.object({retentionDays:z76.number().int().positive(),canUseExtendedDateRanges:z76.boolean()}).optional(),history:z76.object({retentionDays:z76.number().int().positive()}).optional(),members:z76.object({canInvite:z76.boolean(),maxMembers:z76.number().int().positive().nullable()}).optional(),projects:z76.object({maxProjects:z76.number().int().positive().nullable()}).optional(),domains:z76.object({canUseCustomDomains:z76.boolean(),maxDomains:z76.number().int().nonnegative().nullable()}).optional(),media_storage:z76.object({limitBytes:z76.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z76.object({usedBytes:z76.number().int().nonnegative().nullable(),limitBytes:z76.number().int().nonnegative().nullable(),state:z76.enum(["ready","unavailable"]),measuredAt:z76.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z76.object({toPlanCode:TemplateCodeSchema,effectiveAt:z76.string(),scheduledAt:z76.string().nullable()}),AutomaticSpendStopDTOSchema=z76.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z76.string(),spendStopped:z76.boolean(),settlementEndsAt:z76.string()}),HostingOverageStatusDTOSchema=z76.object({state:z76.enum(["ready","unavailable"]),planCode:z76.string(),overageAvailable:z76.boolean(),overageEnabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().nullable(),agentRuntimeEnabled:z76.boolean(),agentRuntimeAvailable:z76.boolean(),periodStart:z76.iso.datetime().nullable(),periodEnd:z76.iso.datetime().nullable(),usedBytes:z76.number().nonnegative().nullable(),includedBytes:z76.number().nonnegative().nullable(),overageBytes:z76.number().nonnegative(),currentOverageAmountMicros:z76.number().nonnegative().nullable(),agentRuntimeAmountMicros:z76.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z76.number().nonnegative().nullable(),currency:z76.string().nullable(),status:z76.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z76.object({enabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().max(1e6).optional(),agentRuntimeEnabled:z76.boolean().optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z76.object({id:z76.string(),external_id:z76.string(),customerId:z76.string(),planId:z76.string(),planCode:z76.union([TemplateCodeSchema,z76.literal("Unknown")]),currentPeriod:z76.object({start:z76.string(),end:z76.string().nullable()}),cancelAt:z76.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z76.string(),nextPaymentAt:z76.string().nullable(),baseAmount:z76.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z76.object({totalCap:z76.number(),dailyCap:z76.number(),usedTotal:z76.number()}),CreditBalanceDTOSchema=z76.object({total:z76.number(),base:z76.number(),dailyBase:z76.number(),purchases:z76.number(),awards:z76.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z76.object({total:z76.number(),nearLimit:z76.boolean(),canChat:z76.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z76.object({dailyFreeAvailable:z76.number(),monthlyAvailable:z76.number(),purchasedAvailable:z76.number(),awardedAvailable:z76.number()}),ProjectDailyCreditAllowanceDTOSchema=z76.object({periodCap:z76.number(),dailyGrant:z76.number(),usedThisPeriod:z76.number(),remainingThisPeriod:z76.number()}),ProjectCreditBalanceDTOSchema=z76.object({projectId:z76.uuid(),organizationId:z76.string(),balance:z76.object({totalAvailable:z76.number(),nearLimit:z76.boolean(),canUseAi:z76.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z76.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z76.enum(["ok","near_limit","exhausted"]),AgentRuntimeOverageRefusalSchema=z76.enum(["plan_unknown","plan_cannot_fund","pending_plan_exit","consent_missing"]),AgentRuntimeOverageDTOSchema=z76.object({available:z76.boolean(),enabled:z76.boolean(),status:z76.enum(["included","paid","paused"]),pauseReason:AgentRuntimeOverageRefusalSchema.nullable(),rateUsdPerHour:z76.number().nonnegative().nullable(),monthlyCapUsd:z76.number().positive().nullable(),consentedAt:z76.coerce.date().nullable(),billableMs:z76.number().int().nonnegative(),paidRemainingMs:z76.number().int().nonnegative(),projectedAmountUsd:z76.number().nonnegative().nullable()}),AgentRuntimeUsageDTOSchema=z76.object({planCode:z76.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z76.object({source:z76.enum(["cached_subscription","free_fallback"]),settledMs:z76.number().int().nonnegative(),activeMs:z76.number().int().nonnegative(),reservedMs:z76.number().int().nonnegative().optional(),includedMs:z76.number().int().positive(),remainingMs:z76.number().int().nonnegative(),extraMs:z76.number().int().nonnegative(),resetsAt:z76.coerce.date()}),overage:AgentRuntimeOverageDTOSchema}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().nonnegative(),refillAmountUsd:z76.number().nonnegative()}),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().nonnegative().nullable(),refillAmountUsd:z76.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().min(.01).multipleOf(.01),refillAmountUsd:z76.number().min(.01).multipleOf(.01),expectedRateToken:z76.string().trim().min(1).max(40)}).strict(),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().min(.01).multipleOf(.01),expectedRateToken:z76.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z76.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z76.object({planCode:z76.union([TemplateCodeSchema,z76.literal("Unknown")]).nullable(),canPurchase:z76.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z76.number().int().positive(),minAmountUsd:z76.number().positive(),maxAmountUsd:z76.number().positive(),rateToken:z76.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z76.object({amountUsd:z76.number(),idempotencyKey:z76.string().trim().min(8).max(120),expectedRateToken:z76.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z76.object({invoiceId:z76.string(),newBalance:z76.int(),creditCount:z76.int(),amountUsd:z76.number(),creditsPerDollar:z76.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z76.object({url:z76.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z76.object({id:z76.string(),number:z76.string().nullable(),status:z76.string(),amountDue:z76.int(),currency:z76.string(),issuedAt:z76.string().nullable(),hostedInvoiceUrl:z76.string().nullable()}),PaymentRecoveryDTOSchema=z76.discriminatedUnion("status",[z76.object({status:z76.literal("eligible"),checkedAt:z76.string()}),z76.object({status:z76.literal("recovery_required"),checkedAt:z76.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z76.int().min(1)}),z76.object({status:z76.literal("unavailable"),checkedAt:z76.string(),reason:z76.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 z77}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z77.object({brand:z77.string(),last4:z77.string(),exp:z77.string(),isDefault:z77.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z78}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema2,EntryDTO,PaginatedEntriesDTOSchema2,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema2,EntryListResponseSchema,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema2,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema2,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema2,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common2();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z78.string().superRefine((path52,ctx)=>{let segments=path52.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z78.object({type:z78.literal("renameField"),contentType:z78.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z78.object({enabled:z78.boolean()}).strict(),ContentFieldGroupSchema=z78.object({id:z78.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z78.string().min(1).max(255),default:z78.boolean().optional()}).strict(),ContentTypeDTOSchema=z78.object({id:z78.string(),name:z78.string(),label:z78.string(),isSingleton:z78.boolean(),i18n:ContentTypeI18nSchema,groups:z78.array(ContentFieldGroupSchema).default([]),fields:z78.record(z78.string(),FieldDefinitionSchema),createdAt:z78.string(),updatedAt:z78.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z78.object({contentTypes:z78.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z78.object({id:z78.string(),entryId:z78.string(),documentId:z78.string(),slug:z78.string(),locale:z78.string().optional(),createdAt:z78.string(),updatedAt:z78.string(),__fimo:z78.object({contentType:z78.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({limit:z78.number(),offset:z78.number(),total:z78.number(),hasMore:z78.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z78.object({contentType:z78.string(),count:z78.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z78.object({counts:z78.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z78.object({count:z78.number().int().nonnegative(),sourceLocale:z78.string(),targetLocale:z78.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z78.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z78.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z78.union([z78.string(),z78.number(),z78.boolean(),z78.null()]),entryWhereOperatorSchema2=z78.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z78.array(entryWhereScalarSchema2).optional(),$nin:z78.array(entryWhereScalarSchema2).optional(),$contains:z78.string().optional(),$startsWith:z78.string().optional(),$null:z78.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z78.object({data:z78.record(z78.string(),z78.unknown()),locale:z78.string().min(1).optional(),documentId:z78.uuid().optional()}),entryIdsSchema=z78.array(z78.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z78.object({sql:z78.string().min(1)}),BulkCreateEntriesRequestSchema=z78.object({entries:z78.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z78.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z78.object({updates:z78.array(z78.object({id:z78.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,locale:z78.string().min(1).optional()}),z78.object({where:EntryWhereSchema2,locale:z78.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z78.object({data:z78.array(z78.record(z78.string(),z78.unknown())),meta:z78.object({rowCount:z78.number().int().nonnegative(),truncated:z78.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({created:z78.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({updated:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({deleted:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z79}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z79.object({index:z79.number().int().nonnegative(),contentType:z79.string(),field:z79.string(),value:z79.string(),against:z79.enum(["stored","batch"]),ownerDocumentId:z79.uuid().optional(),ownerIndex:z79.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z79.object({code:z79.literal("unique_conflict"),message:z79.string(),conflicts:z79.array(UniqueConflictSchema),truncated:z79.boolean().optional()})}});import{z as z80}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z80.object({kind:z80.literal("unique_conflict"),contentType:z80.string(),field:z80.string(),value:z80.string(),documentCount:z80.number().int().positive(),documentIds:z80.array(z80.uuid()),documentIdsTruncated:z80.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z80.object({code:z80.literal("schema_transition_rejected"),message:z80.string(),issues:z80.array(SchemaTransitionIssueSchema),truncated:z80.boolean().optional()})}});import{z as z81}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common2();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z81.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z81.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z81.object({field:CmsFieldNameSchema,direction:z81.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z81.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z81.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z81.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z81.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z81.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z82}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z82.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z83}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z83.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z83.object({event:ClientTrackedEventSchema,properties:z83.record(z83.string(),z83.unknown()).default({})})}});import{z as z84}from"zod";var AssetPathItemSchema,AssetDTOSchema2,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema2,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common2();init_create_dto();init_response();AssetPathItemSchema=z84.object({id:z84.string(),name:z84.string()}),AssetDTOSchema2=z84.object({id:z84.string(),name:z84.string(),type:AssetTypeSchema,originalFileName:z84.string().nullable(),parentId:z84.string().nullable(),mimeType:z84.string().nullable(),fileSize:z84.number().nullable(),url:z84.string().nullable(),storageKey:z84.string().nullable(),createdAt:z84.string(),updatedAt:z84.string(),altText:z84.string().nullable().optional(),caption:z84.string().nullable().optional(),aiCaption:z84.string().nullable().optional(),aiAltText:z84.string().nullable().optional(),aiTags:z84.array(z84.string()).nullable().optional(),aiPrimaryColor:z84.string().nullable().optional(),aiProcessingStatus:z84.string().nullable().optional(),width:z84.number().nullable().optional(),height:z84.number().nullable().optional(),path:z84.array(AssetPathItemSchema).optional(),hasChildren:z84.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z84.lazy(()=>z84.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z84.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z84.object({error:z84.string(),code:z84.literal("media_storage_limit_exceeded"),usedBytes:z84.number().int().nonnegative(),limitBytes:z84.number().int().positive(),incomingBytes:z84.number().int().nonnegative()}),AssetReferenceScopeSchema=z84.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z84.object({assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z84.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z84.object({totalFiles:z84.number().int().nonnegative(),checkedFiles:z84.number().int().nonnegative(),limit:z84.number().int().positive()}),AssetReferenceFindingDTOSchema=z84.object({assetId:z84.uuid(),entryId:z84.string(),documentId:z84.string(),contentType:z84.string(),locale:z84.string().nullable(),slug:z84.string(),fieldPath:z84.string()}),AssetReferenceScopeResultDTOSchema=z84.object({scope:AssetReferenceScopeSchema,label:z84.string(),state:z84.enum(["available","not-published","failed"]),coverage:z84.enum(["complete","partial","failed"]),referenceCount:z84.number().int().nonnegative().optional(),codeReferenceCount:z84.number().int().nonnegative().optional(),referencedAssetIds:z84.array(z84.uuid()).optional(),references:z84.array(AssetReferenceFindingDTOSchema),reason:z84.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z84.discriminatedUnion("type",[z84.object({type:z84.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z84.object({type:z84.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z84.object({type:z84.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z84.object({replacementAssetId:z84.uuid()}),AssetReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),entriesChanged:z84.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),filesChanged:z84.number().int().nonnegative(),commitSha:z84.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z84.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z84.object({error:z84.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z84.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z84.object({intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z84.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z84.object({id:z84.uuid(),intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()),replacementAssetId:z84.uuid().nullable(),expiresAt:z84.iso.datetime(),undoable:z84.boolean(),requestedByMe:z84.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z84.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z84.object({error:z84.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z85}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z85.object({key:z85.string(),value:z85.string().optional(),defaultValue:z85.string(),locale:z85.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z86}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z86.object({id:z86.string(),name:z86.string(),type:z86.enum(["file","folder"]),path:z86.string(),children:z86.lazy(()=>z86.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z86.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z86.object({path:z86.string(),exists:z86.boolean(),type:z86.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z87}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema2,FormUpdateSchema2,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z87.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z87.object({minLength:z87.number().optional(),maxLength:z87.number().optional(),min:z87.number().optional(),max:z87.number().optional(),pattern:z87.string().optional(),maxFileSize:z87.number().optional(),accept:z87.array(z87.string()).optional()}),FormFieldSchema=z87.object({type:FormFieldTypeSchema,label:z87.string(),placeholder:z87.string().optional(),required:z87.boolean().optional(),defaultValue:z87.string().optional(),options:z87.array(z87.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z87.record(z87.string(),FormFieldSchema),FormContentSchema2=z87.object({name:z87.string().min(1).max(255),label:z87.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z88}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z88.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z88.object({items:z88.array(ProjectMessagePublicDTOSchema),nextCursor:z88.string().nullable()}),ChatLiveTurnDTOSchema=z88.object({invocationId:z88.string(),step:z88.enum(["preparing","working","compacting","merging"]),startedAt:z88.string(),continuesInvocationId:z88.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z88.object({threadId:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z88.object({id:z88.string(),role:z88.enum(["user","assistant"]),parts:z88.array(z88.unknown()),metadata:z88.record(z88.string(),z88.unknown()).nullable(),versionId:z88.string().nullable().optional(),createdAt:z88.date().transform(value=>value.toISOString()),providerMessageId:z88.string().nullable().optional(),invocationId:z88.string().nullable().optional(),invocationStatus:z88.string().nullable().optional(),invocationTerminalReason:z88.string().nullable().optional()}),ChatAttentionDTOSchema=z88.object({type:z88.literal("merge_conflict"),merge:z88.object({mergeId:z88.string().uuid(),projectId:z88.string(),fromBranch:z88.string(),toBranch:z88.string()}),publishAfterMerge:z88.boolean()}),ChatThreadMessagesPageDTOSchema=z88.object({threadId:z88.string().nullable(),title:z88.string().nullable(),messages:z88.array(ChatThreadMessageDTOSchema),nextCursor:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z88.object({kind:z88.literal("replay"),threadId:z88.string(),userMessageId:z88.string()}),ChatQueuedOutcomeDTOSchema=z88.object({kind:z88.literal("queued"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string()}),ChatBusyOutcomeDTOSchema=z88.object({kind:z88.literal("busy"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string().optional()}),ChatRefusedOutcomeDTOSchema=z88.object({kind:z88.literal("refused"),threadId:z88.string(),userMessageId:z88.string(),refusedInvocationId:z88.string(),terminalReason:z88.string()}),ChatNonStreamingOutcomeDTOSchema=z88.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z88.object({success:z88.boolean(),deletedCount:z88.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema2(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z88.object({code:z88.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z88.string()})}});import{z as z89}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common2();init_create_dto();init_response();UploadResultDTOSchema=z89.object({url:z89.string().url(),key:z89.string(),size:z89.number(),contentType:z89.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z90}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z90.object({canAccess:z90.boolean(),permissions:z90.record(z90.string(),z90.boolean()),role:z90.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z91}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z91.string().trim().default(""),sort:z91.enum(["recent","name","relevance"]).default("recent"),category:z91.string().optional()})}});import{z as z92}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common2();init_create_dto();init_response();DomainStatusSchema=z92.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z92.enum(["fimo","external"]),PaymentStatusSchema=z92.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z92.object({id:z92.string().uuid(),domain:z92.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z92.boolean(),price:z92.number().int().nullable(),renewalPrice:z92.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z92.string().nullable(),failureReason:z92.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z92.object({domain:z92.string(),available:z92.boolean(),premium:z92.boolean(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),purchaseType:z92.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z92.object({domain:z92.string(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),premium:z92.boolean(),allowedYears:z92.array(z92.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z92.object({firstName:z92.string().max(100),lastName:z92.string().max(100),companyName:z92.string().max(100).optional(),address1:z92.string().max(255),address2:z92.string().max(255).optional(),city:z92.string().max(100),state:z92.string().max(100),zip:z92.string().max(20),country:z92.string().max(2),phone:z92.string().max(30),email:z92.union([z92.string().email().max(255),z92.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z92.object({firstName:z92.string().min(1).max(100),lastName:z92.string().min(1).max(100),companyName:z92.string().max(100).optional(),address1:z92.string().min(1).max(255),address2:z92.string().max(255).optional(),city:z92.string().min(1).max(100),state:z92.string().min(1).max(100),zip:z92.string().min(1).max(20),country:z92.string().min(1).max(2),phone:z92.string().min(1).max(30),email:z92.string().email().max(255)}),SearchDomainsRequestSchema=z92.object({keyword:z92.string().min(1).max(100),tldFilter:z92.array(z92.string()).optional()}),CheckAvailabilityRequestSchema=z92.object({domains:z92.array(z92.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z92.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z92.object({domain:DomainNameSchema,years:z92.number().int().min(1).max(10).optional().default(3),autoRenew:z92.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z92.object({autoRenew:z92.boolean().optional()}),RenewDomainRequestSchema=z92.object({years:z92.number().int().min(1).max(10).optional().default(1),autoRenew:z92.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z92.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z92.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z92.object({verified:z92.boolean(),email:z92.string().nullable(),verifyBy:z92.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z93}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common2();init_create_dto();init_response();ProjectDomainStatusSchema=z93.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z93.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z93.object({txtName:z93.string().nullable().optional(),txtValue:z93.string().nullable().optional(),httpUrl:z93.string().nullable().optional(),httpBody:z93.string().nullable().optional(),cname:z93.string().nullable().optional(),cnameTarget:z93.string().nullable().optional()}),SSLValidationErrorSchema=z93.object({message:z93.string()}),OwnershipVerificationSchema=z93.object({type:z93.string(),name:z93.string(),value:z93.string()}),ProjectDomainSSLDTOSchema=z93.object({status:z93.string(),method:z93.string().nullable(),type:z93.string().nullable(),validationRecords:z93.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z93.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z93.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z93.enum(["subdomain","apex"]),RedirectConfigSchema=z93.object({type:z93.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z93.string()}).nullable().optional(),ProjectDomainDTOSchema=z93.object({id:z93.string(),hostname:z93.string(),status:z93.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z93.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z93.string(),scdCnameTarget:z93.string().optional(),apexTargets:z93.array(z93.string()),dnsAutoConfigured:z93.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z93.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z93.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z93.object({hostname:z93.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z93.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z93.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z93.object({available:z93.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z93.object({success:z93.boolean(),hostname:z93.string()}))}});import{z as z94}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z94.object({available:z94.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z94.object({slug:z94.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z94.object({subdomain:z94.string(),subdomainUpdatedAt:z94.coerce.date()})),SubdomainSuggestionsQuerySchema=z94.object({base:z94.string().max(100).optional(),max:z94.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z94.object({suggestions:z94.array(z94.string())}))}});import{z as z95}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z95.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z95.object({code:ProjectTransferBlockerCodeSchema,message:z95.string(),count:z95.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z95.object({targetOrganizationId:z95.string().min(1)}),ProjectTransferResultDTO=createDTO(z95.object({projectId:z95.string(),sourceOrganizationId:z95.string(),targetOrganizationId:z95.string(),movedThreads:z95.number().int().nonnegative(),revokedInvites:z95.number().int().nonnegative(),revokedGrants:z95.number().int().nonnegative(),preservedGrants:z95.number().int().nonnegative(),warnings:z95.array(z95.string())}))}});import{z as z96}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema2,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema2,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z96.object({translated:z96.number().int().nonnegative(),total:z96.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z96.object({locale:z96.string(),isDefault:z96.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z96.object({defaultLocale:z96.string(),locales:z96.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z96.object({locale:z96.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z96.object({locale:z96.string().min(1).max(40)}),ProjectLocaleMutationSchema=z96.object({locale:z96.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z96.object({locale:z96.string(),entriesDeleted:z96.number().int().nonnegative(),labelsDeleted:z96.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z97}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z97.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z97.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z97.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z97.number(),credits:z97.number().optional(),billingMode:z97.enum(["fimo-credits","provider-account"]).optional(),confidence:z97.enum(["exact","estimated","metered"]),basis:z97.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z98}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema2,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z98.object({options:z98.record(z98.string(),z98.unknown()),name:z98.string().optional(),parentId:z98.string().nullable().optional(),altText:z98.string().optional(),caption:z98.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z98.string().min(1).optional(),model:z98.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z98.object({jobId:z98.string(),status:z98.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z98.string().nullable().optional(),credits:z98.number().optional(),costUsd:z98.number().optional(),billingMode:z98.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z98.object({error:z98.string(),code:z98.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z98.array(GenerationTaskIdSchema).optional(),availableModels:z98.array(z98.string()).optional(),issues:z98.array(z98.unknown()).optional()})}});import{z as z99}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z99.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z99.object({name:z99.string(),key:z99.string(),description:z99.string(),type:FlagTypeSchema,required:z99.boolean(),defaultValue:z99.unknown().optional(),enumValues:z99.array(z99.string()).optional(),isArray:z99.boolean()}),AssetModelPriceSchema=z99.object({unitPrice:z99.number(),unit:z99.string(),confidence:z99.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z99.object({id:z99.string(),shortName:z99.string(),provider:z99.string(),source:z99.string(),modality:z99.enum(["image","video","audio"]),tags:z99.array(z99.string()),displayName:z99.string(),description:z99.string(),flags:z99.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z99.object({model:z99.string(),costUsd:z99.number(),credits:z99.number(),billingMode:z99.enum(["fimo-credits","provider-account"]),confidence:z99.enum(["exact","estimated","metered"]),basis:z99.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z100}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z100.object({tourId:z100.string(),version:z100.string(),status:z100.string(),completedAt:z100.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z100.array(UserTourDTOSchema))}});import{z as z101}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z101.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z101.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z101.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z101.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z101.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z101.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z101.enum(["user","agent","system"]),SupportReportTagSchema=z101.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z101.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z101.object({organization:z101.object({id:z101.string().trim().min(1).max(255),name:z101.string().trim().max(240).optional()}),project:z101.object({id:z101.uuid(),name:z101.string().trim().max(240).optional(),createdAt:z101.coerce.date().optional()}).optional(),environment:z101.string().trim().max(255).optional(),clientVersion:z101.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z101.object({message:z101.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z101.string().trim().max(200).optional(),limit:z101.coerce.number().int().min(1).max(100).default(50),offset:z101.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z101.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z101.uuid().nullable().optional(),note:z101.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z101.object({message:z101.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z101.object({kind:SupportReportLinkKindSchema,label:z101.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z101.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z101.object({kind:SupportReportActorKindSchema,id:z101.string().nullable(),name:z101.string().nullable()}),SupportReportLinkDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportLinkKindSchema,label:z101.string(),url:SupportReportHttpUrlSchema,externalId:z101.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportEventKindSchema,body:z101.string().nullable(),metadata:z101.record(z101.string(),z101.unknown()),actor:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z101.object({id:z101.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z101.array(z101.string()),source:SupportReportSourceSchema,message:z101.string(),reporter:z101.object({id:z101.string().nullable(),name:z101.string().nullable(),email:z101.string().nullable()}),organization:z101.object({id:z101.string().nullable(),name:z101.string()}),project:z101.object({id:z101.uuid().nullable(),name:z101.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z101.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z101.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z101.string().nullable(),deliveredAt:z101.coerce.date().nullable()}).nullable(),duplicateOfReportId:z101.uuid().nullable(),resolvedAt:z101.coerce.date().nullable(),createdAt:z101.coerce.date(),updatedAt:z101.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z101.string().nullable(),clientVersion:z101.string().nullable(),links:z101.array(SupportReportLinkDTOSchema),events:z101.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z101.object({reports:z101.array(SupportReportSummaryDTOSchema),total:z101.number().int().nonnegative(),statusCounts:z101.object({new:z101.number().int().nonnegative(),in_progress:z101.number().int().nonnegative(),waiting:z101.number().int().nonnegative(),resolved:z101.number().int().nonnegative(),duplicate:z101.number().int().nonnegative(),irrelevant:z101.number().int().nonnegative(),ignored:z101.number().int().nonnegative()}),limit:z101.number().int().positive(),offset:z101.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z101.object({id:z101.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z101.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z102}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z102.iso.datetime({offset:!0}).pipe(z102.coerce.date()),OpsRecentChatInputSchema=z102.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z102.string().trim().min(1).max(255).optional(),limit:z102.coerce.number().int().min(1).max(200).default(100),cursor:z102.string().trim().min(1).max(2e3).optional(),slim:z102.boolean().default(!0),reason:z102.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z102.object({id:z102.string(),threadId:z102.string(),providerMessageId:z102.string().nullable(),invocationId:z102.string().nullable(),env:z102.string().nullable(),role:z102.string(),parts:z102.array(z102.record(z102.string(),z102.unknown())),metadata:z102.object({status:z102.string().optional(),traceUrl:z102.string().optional(),externalFileChanges:z102.array(z102.unknown()).optional()}),stats:z102.object({toolCount:z102.number().int().nonnegative(),failedToolCount:z102.number().int().nonnegative()}),createdAt:z102.iso.datetime({offset:!0}),project:z102.object({id:z102.string(),name:z102.string(),displayName:z102.string().nullable(),organizationId:z102.string().nullable()})}),OpsRecentChatResponseSchema=z102.object({target:z102.object({backendProfile:OpsBackendProfileSchema,projectEnv:z102.string().nullable()}),window:z102.object({from:z102.iso.datetime({offset:!0}),to:z102.iso.datetime({offset:!0})}),messages:z102.object({items:z102.array(OpsRecentChatMessageSchema),nextCursor:z102.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z103}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z103.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z103.literal(!1),reason:z103.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z104}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z104.object({packageManager:z104.string().trim().min(1).max(200).nullable(),trackedLockfiles:z104.array(z104.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z104.string().trim().min(1)}),OpsProjectPackageManagerSchema=z104.object({target:z104.object({backendProfile:OpsBackendProfileSchema,projectId:z104.uuid(),projectEnv:z104.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z105}from"zod";var OPS_AGENT_BRANCH_DISCARD_LIMIT,OpsAgentBranchAllowlistSchema,OpsAgentBranchRecoveredOwnerSchema,OpsAgentBranchDiscardPlanInputSchema,OpsAgentBranchDiscardApplyInputSchema,OPS_AGENT_BRANCH_DISCARD_BLOCKERS,OpsAgentBranchDiscardBlockerSchema,init_ops_agent_branch_discard_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-branch-discard.dto.js"(){"use strict";init_env();OPS_AGENT_BRANCH_DISCARD_LIMIT=25,OpsAgentBranchAllowlistSchema=z105.array(BranchSchema).min(1,"name at least one Branch to discard").max(OPS_AGENT_BRANCH_DISCARD_LIMIT).refine(branches=>new Set(branches).size===branches.length,{error:"the Branch allowlist must not repeat a Branch"}),OpsAgentBranchRecoveredOwnerSchema=z105.object({branch:BranchSchema,sessionId:z105.uuid()}),OpsAgentBranchDiscardPlanInputSchema=z105.object({branches:OpsAgentBranchAllowlistSchema,reason:z105.string().trim().min(1).max(1e3),recoveredOwners:z105.array(OpsAgentBranchRecoveredOwnerSchema).max(OPS_AGENT_BRANCH_DISCARD_LIMIT).optional()}).refine(input=>(input.recoveredOwners??[]).every(owner=>input.branches.includes(owner.branch)),{error:"every recovered owner must name a Branch from the allowlist",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.branch)).size===owners.length},{error:"recovered owners must not repeat a Branch",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.sessionId)).size===owners.length},{error:"recovered owners must not repeat a session",path:["recoveredOwners"]}),OpsAgentBranchDiscardApplyInputSchema=OpsAgentBranchDiscardPlanInputSchema.safeExtend({planHash:z105.string().trim().length(64)}),OPS_AGENT_BRANCH_DISCARD_BLOCKERS=["branch_not_found","not_agent_session_branch","branch_not_active","production_branch","default_branch","production_source_branch","owner_session_missing","not_project_agent_run","open_merge","live_mcp_session","live_owner","has_descendants","recovery_direct_owner_present","recovery_session_not_found","recovery_session_not_project_agent_run","recovery_session_not_terminal","recovery_session_already_bound"],OpsAgentBranchDiscardBlockerSchema=z105.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z106}from"zod";function createAgentRunWebhookEventDataSchema(status){return z106.object({run:z106.object({id:z106.string(),agentName:z106.string(),trigger:z106.string(),status:z106.literal(status),startedAt:z106.string().nullable(),finishedAt:z106.string().nullable(),reason:z106.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common2();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z106.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z106.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z106.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z106.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z106.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z106.object({reason:WebhookEntryChangeReasonSchema,operationId:z106.string().optional(),batch:z106.object({index:z106.number().int().positive(),total:z106.number().int().positive()}).optional(),changes:z106.array(z106.object({action:WebhookEntryChangeActionSchema,contentType:z106.string(),id:z106.string(),documentId:z106.string(),locale:z106.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z106.object({form:z106.object({id:z106.string(),label:z106.string()}),submission:z106.object({id:z106.string(),data:z106.record(z106.string(),z106.unknown()),submittedAt:z106.string()})}),PublishStartedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("publishing"),startedAt:z106.string()})}),PublishSucceededWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("published"),url:z106.string(),publishedAt:z106.string(),firstPublish:z106.boolean()})}),PublishFailedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("failed"),reason:z106.string()})}),PublishUnpublishedWebhookEventDataSchema=z106.object({publication:z106.object({previousUrl:z106.string(),unpublishedAt:z106.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z106.object({review:z106.object({runId:z106.string(),agentName:z106.string(),reason:z106.string()}),source:z106.object({branch:z106.string(),revision:z106.string(),anchorBranch:z106.string()})}),AgentReviewResolvedWebhookEventDataSchema=z106.object({review:z106.object({id:z106.string(),runId:z106.string(),agentName:z106.string(),resolution:z106.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z106.object({report:z106.object({weekStart:z106.string(),weekEnd:z106.string(),pageviews:z106.number(),visitors:z106.number(),previousPageviews:z106.number(),previousVisitors:z106.number()})}),MediaAssetWebhookEventDataSchema=z106.object({id:z106.string().nullable(),name:z106.string().nullable(),type:z106.string(),mimeType:z106.string().nullable(),fileSize:z106.number().nullable()}),MediaUploadedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("updated")}),MediaDeletedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string()})}),LabelChangedWebhookEventDataSchema=z106.object({changes:z106.array(z106.object({action:z106.enum(["created","updated","deleted"]),key:z106.string(),locale:z106.string(),value:z106.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),isDefault:z106.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),previousCode:z106.string()})}),LocaleDeletedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),entriesDeleted:z106.number().int().nonnegative(),labelsDeleted:z106.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z106.object({merge:z106.object({id:z106.string(),from:BranchSchema,to:BranchSchema,applied:z106.array(z106.object({surface:SurfaceNameSchema,count:z106.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z106.object({branch:z106.object({name:BranchSchema}),version:z106.object({versionId:z106.uuid(),name:z106.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"branch.restored":BranchRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z106.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z106.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z106.discriminatedUnion("source",[z106.object({source:z106.literal("literal"),value:z106.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z106.object({source:z106.literal("secret"),key:z106.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z106.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z106.object({name:z106.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z106.object({name:z106.string(),source:z106.enum(["literal","secret"]),secretKey:z106.string().nullable(),secretPrefix:z106.string().nullable(),configured:z106.literal(!0)}),WebhookFilterSchema=z106.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z106.string().min(1).max(255).optional(),agentName:z106.string().min(1).max(120).optional(),mediaType:z106.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z106.string().min(1).max(255).optional(),locale:z106.string().min(1).max(120).optional()}),JsonValueSchema=z106.lazy(()=>z106.union([z106.string(),z106.number(),z106.boolean(),z106.null(),z106.array(JsonValueSchema),z106.record(z106.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z106.url(),enabled:z106.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z106.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z106.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z106.url().optional(),enabled:z106.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z106.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z106.boolean().optional()}),TestProjectWebhookRequestSchema=z106.object({eventType:WebhookEventTypeSchema.optional(),data:z106.record(z106.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z106.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z106.uuid(),name:z106.string(),eventType:WebhookEventTypeSchema,enabled:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z106.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z106.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z106.coerce.date().nullable(),deliveryStats24h:z106.object({succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z106.uuid(),projectId:z106.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z106.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z106.number().int().positive(),test:z106.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z106.number().int().nonnegative(),responseStatus:z106.number().int().nullable(),lastErrorCode:z106.string().nullable(),lastErrorMessage:z106.string().nullable(),payloadAvailable:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z106.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z106.string().nullable(),qstashMessageId:z106.string().nullable(),deliveredAt:z106.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z106.object({items:z106.array(WebhookDeliveryDTOSchema),pagination:z106.object({page:z106.number().int().positive(),limit:z106.number().int().positive(),total:z106.number().int().nonnegative(),totalPages:z106.number().int().positive(),hasMore:z106.boolean()}),stats:z106.object({total:z106.number().int().nonnegative(),succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z106.object({id:z106.uuid(),deliveryId:z106.uuid(),attempt:z106.number().int().positive(),status:z106.enum(["delivering","succeeded","failed"]),responseStatus:z106.number().int().nullable(),durationMs:z106.number().int().nonnegative(),responseExcerpt:z106.string().nullable(),errorCode:z106.string().nullable(),errorMessage:z106.string().nullable(),createdAt:z106.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z106.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z106.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z107}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z107.object({key:z107.literal("fimo-2"),enabled:z107.boolean(),dismissed:z107.boolean().default(!1),interacted:z107.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z108}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common2();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z108.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z108.object({total:z108.number(),base:z108.number(),purchases:z108.number(),awards:z108.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z108.object({id:z108.string(),name:z108.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z108.object({type:z108.string(),brand:z108.string().nullable(),last4:z108.string().nullable(),expirationDate:z108.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z108.object({currency:z108.string(),nextPaymentAmount:z108.number().nullable(),nextPaymentAt:z108.string().nullable(),billingInterval:z108.string().nullable(),totalAmount:z108.number().nullable(),discountAmount:z108.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z108.object({id:z108.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z108.string().nullable(),currentPeriodEndsAt:z108.string().nullable(),renewsAt:z108.string().nullable(),cancelAt:z108.string().nullable(),renewAutomatically:z108.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z108.object({type:z108.enum(["low_balance","critical_balance","approaching_limit"]),message:z108.string(),estimatedPromptsRemaining:z108.number().nullable(),avgCostPerPrompt:z108.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z108.object({monthlyCredits:z108.number().nullable(),usedThisPeriod:z108.number(),remainingThisPeriod:z108.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z108.object({organizationId:z108.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z108.string().nullable(),tenureDays:z108.number().int().nonnegative(),capturedAt:z108.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z108.object({hasSubscription:z108.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z108.number().nullable(),alerts:z108.array(CreditAlertDTOSchema),portalUrl:z108.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z108.object({creditCount:z108.number().int().positive(),expiresAt:z108.string().datetime().nullable().optional(),message:z108.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("free"),amountCents:z108.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("purchase"),amountCents:z108.number().int().positive()}),CreditTopupRequestDTOSchema=z108.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z108.object({success:z108.boolean(),transactionId:z108.string().nullable(),newBalance:z108.number(),creditCount:z108.number(),type:z108.enum(["free","purchase"]),invoiceId:z108.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z109}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z109.object({totalCredits:z109.number(),totalCostUsd:z109.number(),totalMessages:z109.number(),avgCostPerMessage:z109.number(),periodStart:z109.string().nullable(),periodEnd:z109.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z109.object({date:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z109.array(UsageByUserForProjectDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z109.object({summary:UsageSummaryDTOSchema,byProject:z109.array(UsageByProjectDTOSchema),byUser:z109.array(UsageByUserDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z110}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z110.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z110.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z110.object({startDate:z110.string().optional(),endDate:z110.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z110.coerce.number().int().positive().default(1),limit:z110.coerce.number().int().positive().max(100).default(20),sortBy:z110.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z110.string().optional(),activeOnly:z110.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z110.object({totalCredits:z110.number(),totalCostUsd:z110.number(),totalMessages:z110.number(),avgCostPerMessage:z110.number(),avgCreditsPerMessage:z110.number(),periodStart:z110.string(),periodEnd:z110.string(),creditsChange:z110.number().nullable(),costChange:z110.number().nullable(),messagesChange:z110.number().nullable(),unattributedCredits:z110.number(),unattributedCostUsd:z110.number(),unattributedMessages:z110.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z110.object({date:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z110.object({organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number(),projectCount:z110.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z110.object({userId:z110.string(),userName:z110.string().nullable(),userEmail:z110.string().nullable(),userImage:z110.string().nullable(),organizationId:z110.string().nullable(),organizationName:z110.string().nullable(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),projectCount:z110.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z110.object({projectId:z110.string(),projectName:z110.string(),projectDisplayName:z110.string().nullable(),organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z110.object({id:z110.string(),name:z110.string(),value:z110.number(),percentage:z110.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z110.object({day:z110.number(),hour:z110.number(),value:z110.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z110.object({summary:UsageOverviewSummaryDTOSchema,timeline:z110.array(UsageTimelinePointDTOSchema),topOrganizations:z110.array(OrganizationUsageRowDTOSchema),topUsers:z110.array(UserUsageRowDTOSchema),topProjects:z110.array(ProjectUsageRowDTOSchema),creditDistribution:z110.array(UsageDistributionItemDTOSchema),userDistribution:z110.array(UsageDistributionItemDTOSchema),heatmap:z110.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z110.object({page:z110.number(),limit:z110.number(),totalItems:z110.number(),totalPages:z110.number(),hasMore:z110.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z110.object({organizations:z110.array(OrganizationUsageRowDTOSchema),top:z110.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z110.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z110.object({users:z110.array(ExtendedUserUsageRowDTOSchema),top:z110.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z110.object({projects:z110.array(ExtendedProjectUsageRowDTOSchema),top:z110.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z110.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z110.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z110.object({credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),createdAt:z110.string(),memberCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z110.object({id:z110.string(),name:z110.string().nullable(),email:z110.string(),image:z110.string().nullable(),createdAt:z110.string(),organizationCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),displayName:z110.string().nullable(),createdAt:z110.string(),organizationId:z110.string(),organizationName:z110.string(),ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z111}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z111.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z111.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z111.object({command:z111.string().min(1).max(1e4),cwd:z111.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z111.record(z111.string(),z111.string()).optional(),name:z111.string().optional(),waitForCompletion:z111.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z111.object({identifier:z111.string(),status:SandboxProcessStatusSchema,command:z111.string().optional(),startedAt:z111.string().optional(),exitCode:z111.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z111.object({processes:z111.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z111.object({processId:z111.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z111.object({success:z111.boolean(),message:z111.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z112}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common2();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_control_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_hosted_preview_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_branch_discard_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["symbolic-ref","--short","-q","HEAD"],cwd)}async function commitSubjectOrNull(cwd,sha){try{return await runGit(["log","-1","--format=%s",sha,"--"],cwd)}catch{return null}}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function gitErrorSummary(error){let lines=extractStderr(error).split(`
|
|
200
|
-
`).map(line=>line.trim()).filter(line=>line.length>0);return(lines.find(line=>line.startsWith("fatal:")||line.startsWith("error:"))??lines[0]??"git failed").replace(/\/\/[^/\s@]*@/g,"//")}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(commitSubjectOrNull,"commitSubjectOrNull");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(gitErrorSummary,"gitErrorSummary");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveBranchFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{branch:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||!isValidBranch(branch)?null:{branch,source:"branch"}}catch{return null}}function resolveBranchFromEnvironment(){let branch=process.env.FIMO_ENV?.trim();return branch&&isValidBranch(branch)?branch:null}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let branch,source,readOnly=!1;if(opts.branchOverride!==void 0){if(!isValidBranch(opts.branchOverride))throw new InvalidBranchOverrideError(opts.branchOverride);branch=opts.branchOverride,source="flag"}else{let fromGit=await resolveBranchFromGit(cwd);if(fromGit)branch=fromGit.branch,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{let fromEnvironment=resolveBranchFromEnvironment();if(!fromEnvironment)throw new GitBranchUndetectedError;branch=fromEnvironment,source="environment"}}if(opts.fimo&&branch!=="prod")try{let{data:branches}=await opts.fimo.execute("branches.list",{projectId:settings.projectId,includeAgentBranches:!0}),names=branches.map(candidate=>candidate.branch);if(!names.includes(branch)&&source==="flag")throw new BranchNotFoundError(branch,names)}catch(err){if(err instanceof BranchNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,branch,source,readOnly:readOnly||void 0}}function branchSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--branch":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"FIMO_ENV",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 Branch: ${ctx.branch} (from ${sourceHint}${ro})`}function branchOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let branch=cur.opts().branch;if(typeof branch=="string"&&branch.length>0)return branch;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let branchOverride2=branchOverrideFromCommand(cmd),cfg=loadConfig(),baseFimo=createCliFimoClient(cfg),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2,fimo:baseFimo});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${branchSourceBanner(ctx)}
|
|
199
|
+
`)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z46.enum(REPORT_TONES),blockCommon={title:z46.string().trim().min(1).max(120).optional(),fallback:z46.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z46.object({type:z46.literal("text"),...blockCommon,text:z46.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z46.object({type:z46.literal("metric"),...blockCommon,items:z46.array(z46.object({value:z46.string().trim().min(1).max(24),unit:z46.string().trim().min(1).max(12).optional(),label:z46.string().trim().min(1).max(160),note:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z46.array(z46.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z46.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z46.object({type:z46.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z46.string().trim().min(1).max(12).optional(),points:z46.array(z46.object({label:z46.string().trim().min(1).max(24),value:z46.number().finite(),highlight:z46.boolean().optional()}).strict()).min(2).max(24),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z46.object({type:z46.literal("list"),...blockCommon,items:z46.array(z46.object({tone:ReportToneSchema.optional(),label:z46.string().trim().min(1).max(24).optional(),heading:z46.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z46.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z46.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z46.object({type:z46.literal("table"),...blockCommon,columns:z46.array(z46.object({label:z46.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z46.array(z46.object({cells:z46.array(z46.object({text:z46.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z46.object({type:z46.literal("media"),...blockCommon,assetId:z46.uuid(),alt:z46.string().trim().min(1).max(300),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z46.object({type:z46.literal("links"),...blockCommon,items:z46.array(z46.object({label:z46.string().trim().min(1).max(120),url:z46.url({protocol:/^https$/}).max(2e3),description:z46.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z46.object({type:z46.literal("code"),...blockCommon,language:z46.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z46.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z46.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z46.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z46.object({title:z46.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z46.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z46.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z46.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z46.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(normalizeReportDocument,"normalizeReportDocument");__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z47}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z47.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z47.object({dev:z47.string().trim().min(1).optional(),build:z47.string().trim().min(1).optional(),install:z47.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z47.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z47.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z47.object({type:z47.enum(["header","cookie","query","host"]),key:z47.string().min(1).optional(),value:z47.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z47.array(FimoHostingConditionSchema).min(1).optional(),missing:z47.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z47.object({source:z47.string().min(1),destination:z47.string().min(1),permanent:z47.boolean().optional(),statusCode:z47.union([z47.literal(301),z47.literal(302),z47.literal(307),z47.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z47.object({source:z47.string().min(1),headers:z47.array(z47.object({key:z47.string().min(1),value:z47.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z47.object({rewrites:z47.array(FimoHostingRewriteSchema).optional(),redirects:z47.array(FimoHostingRedirectSchema).optional(),headers:z47.array(FimoHostingHeaderSchema).optional(),cleanUrls:z47.boolean().optional(),trailingSlash:z47.boolean().optional()}).strict(),FimoAppConfigSchema=z47.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52,params){return pageRouteParamNames(path52).filter(param=>!LOCALE_PARAM_NAME.test(param)&¶ms?.[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 z48}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,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","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-6-astra","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z48.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z48.string(),displayName:z48.string().nullable(),subdomain:z48.string().nullable().optional(),subdomainUpdatedAt:z48.date().nullable().optional(),organizationId:z48.string().nullable(),createdBy:z48.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),previewEnabled:z48.boolean().default(!0),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z48.string(),thumbnailUrl:z48.string().nullable(),publishedThumbnailUrl:z48.string().nullable(),category:z48.string().nullable(),snapshotUrl:z48.string().startsWith("/").optional(),appUrl:z48.string().nullable(),lastPublishedAt:z48.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z48.object({name:z48.string().optional(),previewEnabled:z48.boolean().optional(),enabledChatModels:z48.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z48.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z48.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z48.object({id:z48.uuid(),name:z48.string(),displayName:z48.string().nullable(),thumbnailUrl:z48.string().nullable(),category:z48.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z48.object({id:z48.string(),name:z48.string(),avatar:z48.string().nullable(),color:z48.object({bg:z48.string(),text:z48.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z48.object({path:z48.string(),content:z48.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z48.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z48.object({id:z48.string(),messageId:z48.string(),versionId:z48.string().nullable(),role:ProjectChatMessageRole,parts:z48.array(z48.any()),createdAt:z48.coerce.date()}),MessageUserMetadataSchema=z48.object({id:z48.string(),name:z48.string().nullable().optional(),image:z48.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z48.number(),metadata:z48.object({user:MessageUserMetadataSchema,changeManifest:z48.array(z48.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z48.object({versionId:z48.uuid(),commitHash:z48.string(),name:z48.string(),description:z48.string().nullable(),kind:z48.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z48.object({versionCount:z48.number().int().nonnegative(),snapshotBytes:z48.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z48.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z48.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z48.object({content:z48.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema2(z48.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema2(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema2(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema2(z48.object({success:z48.boolean(),message:z48.string().optional(),warning:z48.string().optional(),durationMs:z48.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z48.object({code:z48.literal("PUBLISH_UPGRADE_REQUIRED"),message:z48.string(),currentVersion:z48.number().int().positive(),targetVersion:z48.literal(4)}),ProjectLatestPublicationAttemptSchema=z48.object({publicationId:z48.uuid(),status:z48.enum(["queued","building","published","failed","canceled"]),failureCode:z48.string().nullable(),sourceBranch:z48.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z48.object({isPublished:z48.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z48.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z48.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z48.object({label:z48.string().trim().min(1).max(120).optional(),notes:z48.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z48.object({success:z48.boolean(),message:z48.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z48.boolean(),publicationId:z48.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema2(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema2(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema2(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema2(ProjectWithPlanDTOSchema)}});import{z as z49}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common2();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z49.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z49.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z49.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z49.string().nullable(),deletedAt:z49.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z49.object({id:z49.union([z49.literal(PREVIEW_ENVIRONMENT_KEY),z49.uuid()]),name:z49.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z49.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z49.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema2(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema2(z49.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z49.object({surface:z49.enum(["code","schemas","content","translations","assets","forms"]),status:z49.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z49.number().int().nonnegative(),conflictCount:z49.number().int().nonnegative()}),BranchDiffResultSchema=z49.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z49.coerce.date(),surfaces:z49.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z50}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z50.object({projectId:z50.uuid(),name:z50.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z50.literal("production"),sourceBranch:BranchSchema,isPublished:z50.boolean(),url:z50.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z50.literal(PREVIEW_ENVIRONMENT_KEY),kind:z50.literal("preview"),matchedBranchCount:z50.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z50.literal("custom"),matchedBranchCount:z50.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z50.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z50.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema2(z50.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema2(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z50.object({deletedId:z50.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema2(DeleteProjectEnvironmentResultSchema)}});import{z as z51}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z51.object({kind:z51.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z51.object({kind:z51.enum(["variable","secret"]),value:z51.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z51.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z51.object({kind:z51.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z51.object({id:z51.uuid(),projectId:z51.uuid(),key:z51.string(),kind:z51.literal("secret"),exposure:z51.literal("private"),environment:EnvironmentKeySchema,maskedValue:z51.string().optional(),createdAt:z51.date().transform(value=>value.toISOString()),updatedAt:z51.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema2(z51.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema2(ProjectSecretMetadataDTOSchema)}});import{z as z52}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z52.object({success:z52.literal(!0),downloadUrl:z52.string(),expiresAt:z52.string(),fileSize:z52.number(),duration:z52.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z52.object({success:z52.literal(!0),projectId:z52.string(),projectName:z52.string(),displayName:z52.string(),projectUrl:z52.string(),duration:z52.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z52.object({contentTypes:z52.number(),entries:z52.number(),assets:z52.number(),translations:z52.number(),forms:z52.number(),codeFiles:z52.number(),assetFiles:z52.number()}),ImportPreviewSurfaceDTOSchema=z52.object({name:z52.string(),included:z52.boolean(),count:z52.number().optional(),note:z52.string().optional()}),ImportPreviewDTOSchema=z52.object({projectName:z52.string(),displayName:z52.string().nullable(),category:z52.string().nullable(),exportedAt:z52.string(),version:z52.string(),envScope:z52.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z52.array(ImportPreviewSurfaceDTOSchema),fileSize:z52.number(),fileName:z52.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z52.object({success:z52.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z53}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z53.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z53.object({type:z53.literal("manual")}),ScheduleTriggerSchema=z53.object({type:z53.literal("schedule"),cron:z53.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z53.string().optional()}),WebhookTriggerSchema2=z53.object({type:z53.literal("webhook"),path:z53.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z53.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z54}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z54.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z54.object({token:z54.string().min(1),risk:CapabilityRiskTierSchema,description:z54.string()}),AgentSubAgentSummarySchema=z54.object({name:z54.string().min(1),grant:z54.enum(["inherit","explicit"]),effectiveCaps:z54.array(z54.string().min(1))}),AgentInstallSummaryDTOSchema=z54.object({agentName:z54.string().min(1),env:z54.string().min(1),declaredCapabilities:z54.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z54.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z54.array(CapabilitySummaryEntrySchema),criticalCapabilities:z54.array(CapabilitySummaryEntrySchema),subAgents:z54.array(AgentSubAgentSummarySchema),declaresDelegate:z54.boolean(),cycle:z54.array(z54.string()).nullable(),missingSubAgents:z54.array(z54.string()),warnings:z54.array(z54.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema2(AgentInstallSummaryDTOSchema)}});import{z as z55}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,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=z55.object({kind:TriggerKindSchema,summary:z55.string()}),AgentListItemTriggerStateSchema=z55.object({triggerIndex:z55.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z55.boolean(),wired:z55.boolean(),syncError:z55.string().nullable()}),AgentListItemAvailabilitySchema=z55.enum(["available","pending_merge"]),AgentListItemDTOSchema=z55.object({name:z55.string().min(1),description:z55.string().nullable(),goalFirstLine:z55.string().nullable(),declaredCapabilities:z55.array(CapabilitySummaryEntrySchema),triggers:z55.array(AgentListItemTriggerSchema),triggerStates:z55.array(AgentListItemTriggerStateSchema),availability:AgentListItemAvailabilitySchema,paused:z55.boolean(),nextRunAt:z55.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema2(z55.array(AgentListItemDTOSchema))}});import{z as z56}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,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=z56.object({paused:z56.boolean(),cancelledRuns:z56.number().int().nonnegative(),stopIncomplete:z56.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema2(AgentControlResultSchema),AgentDeleteResultSchema=z56.object({name:z56.string(),removedFiles:z56.number().int().positive(),commitSha:z56.string().nullable(),cancelledRuns:z56.number().int().nonnegative()}),AgentDeleteResultDTO=createDTO(AgentDeleteResultSchema),AgentDeleteResultResponseSchema=createResponseSchema2(AgentDeleteResultSchema)}});import{z as z57}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z57.object({args:z57.unknown().optional(),requestId:z57.string().min(1).max(128).optional()}),DispatchSkippedSchema=z57.object({skipped:z57.enum(["no-manual-trigger","agent-not-deployed","agent-config-invalid","manual-trigger-not-synced","trigger-not-wired","agent-paused","run-in-progress","task-branch-budget","insufficient-credits"])}),DispatchAcceptedSchema=z57.object({sessionId:z57.string().min(1)}),ManualRunResponseSchema=createResponseSchema2(z57.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z58}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z58.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z58.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z58.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z58.object({verb:SurfaceDeltaVerbSchema,key:z58.string(),detail:z58.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z58.record(z58.string(),z58.unknown()).optional()}),PerSurfaceDeltaSchema=z58.object({surface:SurfaceNameSchema,status:z58.enum(["ok","timed_out","failed","unchanged"]),durationMs:z58.number().int().nonnegative().optional(),changedCount:z58.number().int().nonnegative(),conflictCount:z58.number().int().nonnegative(),items:z58.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z58.boolean().optional(),error:z58.string().optional()}),CrossSurfaceFindingSchema=z58.object({id:z58.string(),kind:z58.string(),description:z58.string(),severity:z58.enum(["warning","error"]),source:z58.object({surface:SurfaceNameSchema,key:z58.string()}),target:z58.object({surface:SurfaceNameSchema,key:z58.string()}),actions:z58.array(z58.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z58.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z58.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),agents:z58.array(z58.object({id:z58.string(),name:z58.string(),status:z58.enum(["active","paused","failed"]),lastRunAt:z58.coerce.date().nullable()})).optional(),crossSurface:z58.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema2(StatusReportSchema),DiffReportSchema=z58.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z58.coerce.date(),surfaces:z58.array(PerSurfaceDeltaSchema),crossSurface:z58.array(CrossSurfaceFindingSchema).optional(),fingerprint:z58.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema2(DiffReportSchema),CodeFileDiffSchema=z58.object({path:z58.string(),state:z58.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z58.string(),additions:z58.number().int().nonnegative(),deletions:z58.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema2(CodeFileDiffSchema),CodeConflictBlobSchema=z58.object({oid:z58.string().optional(),content:z58.string().optional(),truncated:z58.boolean(),binary:z58.boolean()}),CodeConflictDetailSchema=z58.object({path:z58.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z58.string(),targetTipSha:z58.string(),mergeBaseSha:z58.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema2(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z58.object({id:z58.string(),slug:z58.string(),contentType:z58.string(),data:z58.record(z58.string(),z58.unknown()),updatedAt:z58.coerce.date()}),ContentRowDiffSchema=z58.object({collection:z58.string(),rowId:z58.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema2(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z58.object({name:z58.string(),label:z58.string(),isSingleton:z58.boolean(),fields:z58.record(z58.string(),z58.unknown())}),SchemaTypeDiffSchema=z58.object({typeName:z58.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema2(SchemaTypeDiffSchema),AssetSnapshotSchema=z58.object({id:z58.string(),name:z58.string(),type:z58.enum(["file","folder"]),mimeType:z58.string().nullable(),storageKey:z58.string().nullable(),url:z58.string().nullable(),fileSize:z58.number().nullable(),width:z58.number().nullable(),height:z58.number().nullable(),altText:z58.string().nullable(),caption:z58.string().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),AssetDiffSchema=z58.object({assetId:z58.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema2(AssetDiffSchema),TranslationRowDiffSchema=z58.object({locale:z58.string(),key:z58.string(),parent:z58.string().nullable(),child:z58.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema2(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z58.object({formName:z58.string(),label:z58.string().nullable(),schemaFingerprint:z58.string(),fields:z58.record(z58.string(),z58.unknown()),settings:z58.record(z58.string(),z58.unknown()).optional()}),FormSchemaDiffSchema=z58.object({formName:z58.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema2(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z58.enum(CONFLICT_KINDS),ConflictSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),kind:ConflictKindSchema.optional(),description:z58.string(),parentValue:z58.unknown().optional(),childValue:z58.unknown().optional(),conflictingFields:z58.array(z58.string()).optional(),code:z58.object({path:z58.string(),unresolvable:z58.boolean().optional(),reason:z58.string().optional()}).optional()}),FieldPickSchema=z58.object({field:z58.string(),choice:z58.enum(["parent","child","pick","ai-pick"]),pickedValue:z58.unknown().optional(),aiSessionId:z58.string().optional()}),ConflictResolutionSchema=z58.object({surface:SurfaceNameSchema,key:z58.string(),choice:z58.enum(["parent","child","pick"]),pickedValue:z58.unknown().optional(),fieldPicks:z58.array(FieldPickSchema).optional()}),MergeResultSchema=z58.object({ok:z58.boolean(),mergeId:z58.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()})),conflicts:z58.array(ConflictSchema).optional(),summary:z58.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema2(MergeResultSchema),EngineStrategySchema=z58.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z58.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z58.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z58.boolean().optional()}),ResolvedStrategySchema=z58.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z58.boolean()}),MergeRequestSchema=z58.object({from:BranchSchema,allowDirectMerge:z58.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z58.object({mergeId:z58.string().uuid(),streamUrl:z58.string(),strategy:ResolvedStrategySchema,acceptedAt:z58.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema2(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z58.object({mergeId:z58.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z58.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z58.array(ConflictSchema),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedBy:z58.string().nullable(),lastEditedAt:z58.coerce.date().nullable(),initiator:z58.object({userId:z58.string().nullable(),role:z58.string().nullable(),agentName:z58.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema2(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z58.object({resolutions:z58.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z58.object({mergeId:z58.string().uuid(),draftResolutions:z58.array(ConflictResolutionSchema),lastEditedAt:z58.coerce.date(),lastEditedBy:z58.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z58.object({mergeId:z58.string().uuid(),resolutions:z58.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z58.object({mergeId:z58.string().uuid()}),PublishReleaseRequestSchema=z58.object({version:z58.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z58.string().max(2e4).optional()}),PublishReleaseResultSchema=z58.object({releaseTag:z58.string(),sha:z58.string(),publishedAt:z58.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema2(PublishReleaseResultSchema)}});import{z as z59}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z59.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z59.enum(["in-progress","done","merged","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z59.strictObject({branch:BranchSchema.optional(),project_agents_only:z59.coerce.boolean().optional(),agent_name:z59.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z59.coerce.date().optional(),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(200).default(25),cursor:z59.coerce.date().optional()}),SessionMetricsSchema=z59.object({cpuMs:z59.number().nonnegative().default(0),netBytes:z59.number().nonnegative().default(0),walltimeMs:z59.number().nonnegative().default(0),llmTokensIn:z59.number().nonnegative().optional(),llmTokensOut:z59.number().nonnegative().optional(),stepCount:z59.number().int().nonnegative().optional(),toolCallCounts:z59.record(z59.string().min(1).max(120),z59.number().int().nonnegative()).optional(),toolCallOutcomes:z59.array(z59.object({toolName:z59.string().min(1).max(120),success:z59.boolean(),code:z59.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z59.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z59.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z59.object({capturedAt:z59.coerce.date(),fingerprint:z59.string().min(1).max(256),counts:z59.object({code:z59.number().int().nonnegative(),content:z59.number().int().nonnegative(),schemas:z59.number().int().nonnegative(),labels:z59.number().int().nonnegative(),assets:z59.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z59.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z59.object({diff:DiffReportSchema,code:z59.array(CodeFileDiffSchema.extend({raw:z59.string().max(24576)})).max(200),schemas:z59.array(SchemaTypeDiffSchema).max(200),content:z59.array(z59.object({key:z59.string().min(1).max(512),collection:z59.string().min(1).max(256),slug:z59.string().max(512).optional(),verb:z59.enum(["added","modified","deleted"]),fields:z59.array(z59.object({name:z59.string().min(1).max(256),before:z59.unknown().optional(),after:z59.unknown().optional()})).max(20)})).max(200),labels:z59.array(z59.object({key:z59.string().min(1).max(512),locale:z59.string().min(1).max(64).optional(),before:z59.unknown().nullable(),after:z59.unknown().nullable()})).max(200),assets:z59.array(z59.object({key:z59.string().min(1).max(512),name:z59.string().min(1).max(512),verb:z59.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema2(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z59.strictObject({id:z59.uuid(),projectId:z59.uuid(),branch:BranchSchema,agentName:z59.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z59.unknown().optional(),capabilities:z59.array(z59.string()).optional(),dataSources:z59.array(z59.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z59.string().nullable(),startedAt:z59.coerce.date().nullable(),finishedAt:z59.coerce.date().nullable(),cancelledAt:z59.coerce.date().nullable(),costUsd:z59.number().nonnegative(),costCeilingUsd:z59.number().nonnegative(),creditsUsed:z59.number().int().nonnegative().nullable(),limitCredits:z59.number().int().nonnegative().nullable(),metrics:SessionMetricsSchema.nullable(),lastCheckpointId:z59.uuid().nullable(),agentBranchId:z59.uuid().nullable(),parentSessionId:z59.uuid().nullable(),terminalReason:z59.string().nullable(),errorMessage:z59.string().nullable(),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z59.string().nullable(),retainedBranch:BranchSchema.nullable().optional(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z59.object({id:z59.uuid(),sessionId:z59.uuid(),checkpointIdx:z59.number().int().nonnegative(),payloadRef:z59.string(),payloadSizeBytes:z59.number().int().nonnegative(),checksum:z59.string().length(64),createdAt:z59.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema2(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema2(z59.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema2(z59.object({session:AgentSessionDTOSchema,checkpoints:z59.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z59.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","agent_run_in_progress","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z59.object({reason:z59.string().min(1).max(120).optional()})}});import{z as z60}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z60.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z60.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z60.object({id:z60.uuid(),envId:z60.uuid(),sessionId:z60.uuid().nullable(),skillName:z60.string().min(1),classification:AgentBranchClassificationSchema,rationale:z60.string().nullable(),summary:z60.string().nullable(),surfaceDeltas:z60.record(z60.string(),z60.unknown()),createdAt:z60.coerce.date(),decidedAt:z60.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z60.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z60.object({path:z60.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema2(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema2(z60.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z60.object({code:z60.literal("merge_conflict"),message:z60.string(),conflicts:z60.record(z60.string(),z60.number().int().nonnegative())})}});import{z as z61}from"zod";function agentQuestionCapabilityDecision(request,answer){let answers=answer?.answer.questions??[],decision={requested:[],approved:[],denied:[]};return request.block.steps.forEach((step,index)=>{if(step.body.type!=="capabilities")return;let answered=answers.find(item=>item.stepId===step.id)??answers[index],selected=new Set(answered?.selectedLabels??[]);for(let item of step.body.items)decision.requested.push(item),(selected.has(item.label)?decision.approved:decision.denied).push(item.token)}),decision}var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z61.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z61.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z61.object({description:z61.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z61.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z61.object({id:z61.uuid(),projectId:z61.uuid(),threadId:z61.uuid(),invocationId:z61.uuid(),agentKey:z61.string().min(1).max(120),anchorEnv:z61.string().min(1).max(64),retainedEnv:z61.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z61.string().min(1).nullable(),continuationInvocationId:z61.uuid().nullable(),askedAt:z61.coerce.date(),expiresAt:z61.coerce.date(),closedAt:z61.coerce.date().nullable()});__name(agentQuestionCapabilityDecision,"agentQuestionCapabilityDecision");AgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema2(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z61.object({questionId:z61.uuid(),invocationId:z61.uuid(),askedAt:z61.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema2(z61.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z61.object({question:AgentQuestionSchema,continuationInvocationId:z61.uuid(),deduped:z61.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema2(AnswerAgentQuestionResultSchema)}});import{z as z62}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z62.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z62.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z62.enum(["secret_text"]),IntegrationCredentialUsageSchema=z62.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z62.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z62.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z62.object({mode:IntegrationAuthModeSchema,label:z62.string().min(1),description:z62.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z62.object({id:z62.string().min(1),label:z62.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z62.boolean()}),IntegrationToolDefinitionDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),description:z62.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z62.object({title:z62.string().min(1),description:z62.string().min(1),command:z62.string().min(1).optional()}),IntegrationInfoDTOSchema=z62.object({key:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),type:z62.enum(["native","mcp"]).optional(),url:z62.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z62.array(IntegrationAuthModeDTOSchema),credentials:z62.array(IntegrationCredentialDefinitionDTOSchema),tools:z62.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z62.enum(["available","unavailable"]).optional(),connectionCapabilities:z62.object({customIdentityCreation:z62.boolean()}).optional(),recipes:z62.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),name:z62.string().min(1),summary:z62.string().min(1),installed:z62.boolean(),enabled:z62.boolean(),setupState:z62.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z62.string().nullable(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),connectionStatus:z62.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),installedAt:z62.coerce.date().nullable(),updatedAt:z62.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),enabled:z62.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z62.string(),connectionId:z62.uuid().nullable().optional(),connectionAlias:z62.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z62.array(z62.string()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z62.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z62.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z62.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z62.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z62.object({id:z62.uuid(),organizationId:z62.string().min(1),integrationKey:z62.string().min(1),registrationId:z62.uuid().nullable(),alias:z62.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z62.string().min(1),externalAccountName:z62.string().nullable(),externalBotUserId:z62.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z62.array(z62.string()),connectedAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z62.boolean(),isDefault:z62.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z62.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z62.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z62.record(McpHeaderNameSchema,z62.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z62.object({alias:z62.string().min(1).max(120).optional(),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z62.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z62.object({displayName:z62.string().trim().min(1).max(35),backgroundColor:z62.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z62.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),alias:z62.string().min(1).max(120),token:z62.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z62.boolean().optional()}),z62.object({mode:z62.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z62.boolean().optional(),registrationId:z62.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z62.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z62.union([z62.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z62.object({type:z62.literal("mcp"),name:z62.string().trim().min(1).max(120),url:z62.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z62.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z62.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z62.object({integrationKey:z62.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z62.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z62.literal("oauth"),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),ReusableMcpServerAuthKindSchema=z62.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z62.object({id:z62.uuid(),name:z62.string().min(1),host:z62.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z62.string().min(1),availability:z62.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z62.object({query:z62.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z62.object({serverId:z62.uuid()}),LinearOAuthApplicationDistributionSchema=z62.enum(["private","public"]),OrganizationLinearAppDTOSchema=z62.object({id:z62.uuid(),displayName:z62.string().min(1),description:z62.string().nullable(),iconUrl:z62.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z62.enum(["active","revoked"]),connectionIds:z62.array(z62.uuid()),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z62.object({appName:z62.string().trim().min(2).max(80),description:z62.string().trim().max(1e3).optional(),iconUrl:z62.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z62.object({projectId:z62.uuid(),registrationId:z62.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z62.object({integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z62.discriminatedUnion("mode",[z62.object({mode:z62.literal("personal"),integrationKey:z62.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z62.object({mode:z62.literal("oauth"),integrationKey:z62.string().min(1),connectUrl:z62.string().url(),expiresAt:z62.coerce.date()})]),BindProjectChannelRequestSchema=z62.object({ref:z62.string().min(1),connectionAlias:z62.string().min(1).optional(),agentName:z62.string().min(1).max(160).nullable().optional(),force:z62.boolean().optional()}),ListProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1)}),SearchProjectChannelsQuerySchema=z62.object({integrationKey:z62.string().min(1),connectionAlias:z62.string().min(1),query:z62.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z62.object({id:z62.uuid(),projectId:z62.uuid(),integrationKey:z62.string().min(1),connectionId:z62.uuid(),externalWorkspaceId:z62.string().min(1),externalChannelId:z62.string().min(1),externalChannelName:z62.string().nullable(),agentName:z62.string().nullable(),enabled:z62.boolean(),createdAt:z62.coerce.date(),updatedAt:z62.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z62.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z62.object({id:z62.string().min(1),name:z62.string().min(1),visibility:z62.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z62.string().min(1).nullable(),canMove:z62.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z62.object({markdown:z62.boolean().optional(),summary:z62.boolean().optional(),links:z62.boolean().optional(),branding:z62.boolean().optional(),images:z62.boolean().optional(),html:z62.union([z62.literal("cleaned"),z62.literal("raw"),z62.boolean()]).optional(),json:z62.union([z62.boolean(),z62.object({prompt:z62.string().min(1).max(1e4),schema:z62.record(z62.string(),z62.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z62.object({url:z62.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z62.object({query:z62.string().min(1),maxResults:z62.number().int().positive().max(20).optional(),sources:z62.array(z62.enum(["web","news","images"])).min(1).max(3).optional(),categories:z62.array(z62.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z62.enum(["hour","day","week","month","year"]).optional(),location:z62.string().min(1).max(160).optional(),country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(100).optional(),types:z62.array(z62.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),sources:z62.array(z62.string().min(1).max(512)).min(1).max(20).optional(),passages:z62.number().int().min(1).max(5).optional(),skills:z62.literal("only").optional(),language:z62.string().min(1).optional(),topic:z62.string().min(1).optional(),license:z62.string().min(1).optional(),minStars:z62.number().int().min(0).optional(),maxStars:z62.number().int().min(0).optional(),archived:z62.boolean().optional(),fork:z62.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z62.object({query:z62.string().min(1).max(500),maxResults:z62.number().int().min(1).max(500).optional(),authors:z62.array(z62.string().min(1)).min(1).optional(),categories:z62.array(z62.string().min(1)).min(1).optional(),from:z62.iso.date().optional(),to:z62.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),query:z62.string().min(1).max(500).optional(),maxPassages:z62.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z62.object({paperId:z62.string().min(1).max(512),intent:z62.string().min(1).max(500),mode:z62.enum(["similar","citers","references"]).optional(),maxResults:z62.number().int().min(1).max(500).optional(),rerank:z62.boolean().optional(),anchors:z62.array(z62.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z62.object({url:z62.string().url(),search:z62.string().min(1).optional(),limit:z62.number().int().positive().max(200).optional(),includeSubdomains:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z62.object({url:z62.string().url(),limit:z62.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z62.object({text:z62.string().min(1).max(200).optional(),cron:z62.string().min(1).max(120).optional(),timezone:z62.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z62.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z62.boolean().optional(),timeoutMs:z62.number().int().positive().max(12e4).optional(),waitForMs:z62.number().int().min(0).max(3e4).optional(),maxAgeMs:z62.number().int().min(0).optional(),minAgeMs:z62.number().int().min(0).optional(),storeInCache:z62.boolean().optional(),proxy:z62.enum(["basic","enhanced","auto"]).optional(),mobile:z62.boolean().optional(),location:z62.object({country:z62.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z62.array(z62.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z62.union([z62.object({type:z62.enum(["scrape","crawl"]).default("scrape"),urls:z62.array(z62.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z62.object({type:z62.literal("search"),queries:z62.array(z62.string().min(1).max(256)).min(1).max(12),searchWindow:z62.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z62.number().int().min(1).max(50).optional(),includeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z62.array(z62.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z62.object({name:z62.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),notification:z62.object({email:z62.object({enabled:z62.boolean().default(!0),recipients:z62.array(z62.string().email()).min(1).max(20),includeDiffs:z62.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z62.object({monitorId:z62.string().uuid(),name:z62.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z62.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z62.string().min(1).max(2e3).optional(),judgeEnabled:z62.boolean().optional(),retentionDays:z62.number().int().min(1).max(365).optional(),status:z62.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z62.object({monitorId:z62.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z62.string().uuid()}),RunProjectIntegrationToolRequestSchema=z62.object({tool:z62.string().min(1),input:z62.record(z62.string(),z62.unknown()),connectionAlias:z62.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z62.object({provider:z62.string().min(1),providerCredits:z62.number().nonnegative().optional(),providerCostUsd:z62.number().nonnegative().optional(),requests:z62.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z62.object({credits:z62.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),json:z62.unknown().optional(),branding:z62.record(z62.string(),z62.unknown()).optional(),warning:z62.string().optional()}),FirecrawlSearchToolOutputSchema=z62.object({query:z62.string(),provider:z62.literal("firecrawl"),warning:z62.string().optional(),results:z62.array(z62.object({title:z62.string(),url:z62.string(),snippet:z62.string().optional(),content:z62.string().optional(),score:z62.number().optional(),publishedAt:z62.string().optional()}))}),FirecrawlResearchPaperSchema=z62.object({paperId:z62.string(),primaryId:z62.string().optional(),ids:z62.record(z62.string(),z62.array(z62.string())).optional(),title:z62.string().optional(),abstract:z62.string().optional(),score:z62.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z62.object({text:z62.string(),score:z62.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(z62.object({id:z62.string(),type:z62.string().min(1).optional(),url:z62.string(),title:z62.string().optional(),passages:z62.array(z62.object({text:z62.string()}).passthrough())}).passthrough()),coverage:z62.record(z62.string(),z62.string()).optional(),reranked:z62.boolean().optional(),repos:z62.array(z62.record(z62.string(),z62.unknown())).optional(),sources:z62.array(z62.record(z62.string(),z62.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),paper:z62.record(z62.string(),z62.unknown()),paperId:z62.string().optional(),query:z62.string().optional(),passages:z62.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),results:z62.array(FirecrawlResearchPaperSchema),poolSize:z62.number().int().nonnegative(),truncated:z62.boolean(),note:z62.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),count:z62.number(),links:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),description:z62.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z62.object({url:z62.string(),provider:z62.literal("firecrawl"),total:z62.number(),pages:z62.array(z62.object({url:z62.string(),title:z62.string().optional(),statusCode:z62.number().optional(),markdown:z62.string().optional(),summary:z62.string().optional(),links:z62.array(z62.string()).optional(),images:z62.array(z62.string()).optional(),html:z62.string().optional(),warning:z62.string().optional()})),warning:z62.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z62.object({cron:z62.string().optional(),text:z62.string().optional(),timezone:z62.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z62.object({id:z62.string().optional(),type:z62.enum(["scrape","crawl","search"]).optional(),urls:z62.array(z62.string()).optional(),queries:z62.array(z62.string()).optional(),searchWindow:z62.string().optional(),maxResults:z62.number().optional(),includeDomains:z62.array(z62.string()).optional(),excludeDomains:z62.array(z62.string()).optional(),scrapeOptions:z62.record(z62.string(),z62.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z62.object({id:z62.string(),name:z62.string(),status:z62.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z62.string().nullable().optional(),lastRunAt:z62.string().nullable().optional(),currentCheckId:z62.string().nullable().optional(),targets:z62.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z62.string().nullable().optional(),judgeEnabled:z62.boolean().optional(),estimatedCreditsPerMonth:z62.number().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z62.object({id:z62.string(),monitorId:z62.string(),scheduledFor:z62.string().nullable().optional(),startedAt:z62.string().nullable().optional(),finishedAt:z62.string().nullable().optional(),estimatedCredits:z62.number().nullable().optional(),reservedCredits:z62.number().nullable().optional(),actualCredits:z62.number().nullable().optional(),billingStatus:z62.string().nullable().optional(),summary:z62.object({totalPages:z62.number().optional(),same:z62.number().optional(),changed:z62.number().optional(),new:z62.number().optional(),removed:z62.number().optional(),error:z62.number().optional()}).passthrough().optional(),error:z62.string().nullable().optional(),createdAt:z62.string().optional(),updatedAt:z62.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitors:z62.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),deleted:z62.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),checks:z62.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z62.object({provider:z62.literal("firecrawl"),monitorId:z62.string(),check:FirecrawlMonitorCheckOutputSchema,next:z62.string().optional()}),FirecrawlToolKeySchema=z62.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z62.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z62.object({projectId:z62.uuid(),integrationKey:z62.string().min(1),tool:z62.string().min(1),connectionAlias:z62.string().min(1).nullable().optional(),output:z62.record(z62.string(),z62.unknown()),executedAt:z62.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z62.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z62.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z62.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema2(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema2(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema2(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema2(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema2(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema2(z62.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema2(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema2(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema2(z62.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema2(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema2(z62.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema2(z62.array(ProjectChannelCandidateDTOSchema))}});import{z as z63}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z63.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z63.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z63.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z63.object({userId:z63.string().min(1),name:z63.string(),email:z63.string().min(1),subscribed:z63.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z63.object({maxSubscribers:z63.number().int().positive(),subscriberCount:z63.number().int().nonnegative(),effectiveRecipientCount:z63.number().int().nonnegative(),currentUserSubscribed:z63.boolean(),candidates:z63.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema2(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z63.object({userIds:z63.array(z63.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z63.object({topic:UserManagedNotificationTopicSchema,enabled:z63.boolean(),source:z63.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z63.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z63.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z63.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z63.string().nullable(),maskedEmail:z63.string().min(1),applied:z63.boolean(),expiresAt:z63.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema2(ScheduleOptOutStateSchema),FollowedScheduleSchema=z63.object({scheduleId:z63.string().min(1),scheduleName:z63.string(),projectId:z63.string().min(1),projectName:z63.string(),env:z63.string().min(1)}),FollowedSchedulesSchema=z63.object({schedules:z63.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema2(FollowedSchedulesSchema)}});import{z as z64}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common2();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z64.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z64.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z64.uuid(),env:z64.string().min(1),name:z64.string().min(1),cron:z64.string().min(1),command:z64.string().min(1),secretKeys:z64.array(z64.string().min(1)),enabled:z64.boolean(),lastRunAt:z64.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z64.string().nullable(),suspendedAt:z64.coerce.date().nullable().optional(),suspensionReason:z64.string().nullable().optional(),overPolicyReasons:z64.array(z64.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120),cron:z64.string().min(1).max(120),command:z64.string().min(1).max(500),secretKeys:z64.array(ProjectSecretKeySchema).default([]),enabled:z64.boolean().optional()}),UpdateProjectScheduleRequestSchema=z64.object({name:z64.string().min(1).max(120).optional(),cron:z64.string().min(1).max(120).optional(),command:z64.string().min(1).max(500).optional(),secretKeys:z64.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z64.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z64.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z64.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z64.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z64.object({maxRuns:z64.number().int().positive(),retentionDays:z64.number().int().positive().nullable(),outputRetentionDays:z64.number().int().positive(),maxOutputBytes:z64.number().int().positive()}),SchedulePolicyStateSchema=z64.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z64.object({code:z64.enum(["Free","PAYG","Premium","Pro"]),source:z64.enum(["cached_subscription","free_fallback"]),activeSchedules:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().nonnegative()}),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),concurrency:z64.object({used:z64.number().int().nonnegative(),limit:z64.number().int().positive()}),compute:z64.object({settledMs:z64.number().int().nonnegative(),activeMs:z64.number().int().nonnegative(),reservedMs:z64.number().int().nonnegative().optional(),includedMs:z64.number().int().nonnegative(),remainingMs:z64.number().int().nonnegative(),resetsAt:z64.coerce.date()}),upgrade:z64.object({code:z64.literal("Pro"),activeSchedulesLimit:z64.number().int().positive(),minCadenceMinutes:z64.number().int().positive(),maxRunMs:z64.number().int().positive(),maxConcurrentRuns:z64.number().int().positive(),computeIncludedMs:z64.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z64.array(z64.string())}),ProjectScheduleUsageSchema=z64.object({runCount:z64.number().int().nonnegative(),runsWithOutput:z64.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z64.object({id:z64.uuid(),scheduleId:z64.uuid(),projectId:z64.uuid(),env:z64.string().min(1),scheduleName:z64.string().min(1),command:z64.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z64.object({id:z64.string().min(1),name:z64.string().min(1)}).nullable(),queuedAt:z64.coerce.date(),startedAt:z64.coerce.date().nullable(),finishedAt:z64.coerce.date().nullable(),exitCode:z64.number().int().nullable(),errorCode:z64.string().nullable(),error:z64.string().nullable(),outputBytes:z64.number().int().nonnegative(),outputTruncated:z64.boolean(),outputExpiresAt:z64.coerce.date().nullable(),metadataExpiresAt:z64.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z64.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z64.coerce.date().nullable(),items:z64.array(z64.object({key:z64.string().min(1),updatedAt:z64.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z64.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z64.object({trigger:z64.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z64.object({limit:z64.coerce.number().int().min(1).max(100).default(25),cursor:z64.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema2(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z64.object({items:z64.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema2(z64.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema2(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z64.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema2(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z64.object({items:z64.array(ProjectScheduleRunDTOSchema),nextCursor:z64.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema2(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema2(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema2(ProjectScheduleRunDetailDTOSchema)}});import{z as z65}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,PUBLICATION_NOTIFICATION_TOPICS,NOTIFICATION_TOPICS,NotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,SupportedNotificationTopicsSchema,NotificationVisibilityQuerySchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,MAX_QUESTION_DIGEST_PAUSE_DAYS,QuestionDigestPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z65.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z65.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z65.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z65.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z65.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("user"),userId:z65.string().min(1)}).strict(),z65.object({kind:z65.literal("agent"),agentKey:z65.string().min(1).max(120),agentId:z65.uuid().optional()}).strict(),z65.object({kind:z65.literal("system")}).strict()]),NotificationSummarySchema=z65.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z65.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z65.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z65.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z65.discriminatedUnion("topic",[z65.object({topic:z65.literal("agent_question"),questionId:z65.uuid(),title:z65.string().trim().min(1).max(80),description:z65.string().trim().min(1).max(240)}).strict(),z65.object({topic:z65.literal("agent_run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().optional(),proposalId:z65.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("agent_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z65.object({topic:z65.literal("publication_failed"),publicationId:z65.uuid(),sourceBranch:z65.string().trim().min(1).max(120),failureCode:z65.string().trim().min(1).max(64),failedAt:z65.iso.datetime(),firstPublication:z65.boolean()}).strict()]),NotificationEnvelopeSchema=z65.object({id:z65.uuid(),projectId:z65.uuid(),sourceKey:z65.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z65.literal(1),payload:NotificationPayloadSchema,createdAt:z65.coerce.date()}),NotificationRecipientStateSchema=z65.object({id:z65.uuid(),notificationId:z65.uuid(),projectId:z65.uuid(),userId:z65.string().min(1),readAt:z65.coerce.date().nullable(),archivedAt:z65.coerce.date().nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationDeliveryStateSchema=z65.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z65.object({id:z65.uuid(),notificationRecipientId:z65.uuid(),projectId:z65.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z65.number().int().nonnegative(),nextAttemptAt:z65.coerce.date().nullable(),lastAttemptAt:z65.coerce.date().nullable(),sentAt:z65.coerce.date().nullable(),failureCode:z65.string().max(80).nullable(),createdAt:z65.coerce.date(),updatedAt:z65.coerce.date()}),NotificationPreferenceSchema=z65.object({topic:WorkNotificationTopicSchema,channel:z65.literal("email"),enabled:z65.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z65.enum(["default","explicit"])}),NotificationSubjectSchema=z65.discriminatedUnion("kind",[z65.object({kind:z65.literal("question"),questionId:z65.uuid()}).strict(),z65.object({kind:z65.literal("run_outcome"),threadId:z65.uuid(),invocationId:z65.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z65.object({kind:z65.literal("retained_review"),threadId:z65.uuid(),invocationId:z65.uuid().nullable(),proposalId:z65.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z65.object({kind:z65.literal("merge_conflict"),mergeId:z65.uuid(),threadId:z65.uuid().nullable()}).strict(),z65.object({kind:z65.literal("publication"),publicationId:z65.uuid()}).strict()]),NotificationViewSchema=z65.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema2(NotificationViewSchema),NotificationListSchema=z65.object({items:z65.array(NotificationViewSchema),nextCursor:z65.string().nullable(),unreadCount:z65.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema2(NotificationListSchema),SupportedNotificationTopicsSchema=z65.string().max(500).transform(value=>value.split(",").map(topic=>topic.trim()).filter(topic=>NOTIFICATION_TOPICS.includes(topic))),NotificationVisibilityQuerySchema=z65.object({supportedTopics:SupportedNotificationTopicsSchema.optional()}),ListNotificationsQuerySchema=z65.object({supportedTopics:SupportedNotificationTopicsSchema.optional(),topic:NotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z65.string().min(1).max(120).optional(),sourceKey:z65.string().min(1).max(255).optional(),unread:z65.stringbool().optional(),archived:z65.stringbool().optional(),limit:z65.coerce.number().int().min(1).max(100).optional(),cursor:z65.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z65.object({recipient:NotificationRecipientStateSchema,unreadCount:z65.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema2(NotificationStateSchema),UpdateNotificationStateRequestSchema=z65.object({read:z65.boolean().optional(),archived:z65.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived."),MAX_QUESTION_DIGEST_PAUSE_DAYS=90,QuestionDigestPreferenceSchema=z65.object({enabled:z65.boolean(),pausedUntil:z65.coerce.date().nullable(),source:z65.enum(["default","explicit"]).optional()})}});import{z as z66}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,QUESTION_DIGEST_PREFERENCE_ENTRY_ID,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","publishing","schedule","usage","question_digest","marketing"],NotificationPreferenceGroupSchema=z66.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=z66.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z66.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),QUESTION_DIGEST_PREFERENCE_ENTRY_ID="question_digest",MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z66.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z66.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z66.object({enabled:z66.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z66.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z66.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z66.enum(["work_review","publishing","schedule","usage"]),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z66.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),id:z66.literal(QUESTION_DIGEST_PREFERENCE_ENTRY_ID),group:z66.literal("question_digest"),enabled:z66.boolean(),source:PreferenceSourceSchema,pausedUntil:z66.coerce.date().nullable()}).strict(),z66.object({kind:z66.literal("provider_subscription"),id:z66.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z66.literal("marketing"),name:z66.string(),description:z66.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z66.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z66.object({email:EmailNotificationPreferenceSchema,entries:z66.array(NotificationPreferenceEntrySchema),unavailableGroups:z66.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema2(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema2(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z66.object({enabled:z66.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema2(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z66.discriminatedUnion("kind",[z66.object({kind:z66.literal("toggle"),enabled:z66.boolean()}).strict(),z66.object({kind:z66.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z66.object({kind:z66.literal("pause_toggle"),enabled:z66.boolean(),pauseDays:z66.number().int().min(1).max(MAX_QUESTION_DIGEST_PAUSE_DAYS).nullable().optional()}).strict().refine(body=>body.enabled||!body.pauseDays,"Pausing requires the toggle to be enabled."),z66.object({kind:z66.literal("provider_subscription"),enabled:z66.boolean()}).strict()])}});import{z as z67}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z67.object({surface:SurfaceNameSchema,key:z67.string(),label:z67.string()}),InlineSchema=z67.object({text:z67.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z67.discriminatedUnion("type",[z67.object({type:z67.literal("paragraph"),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("preview"),ref:DiffRefSchema,caption:z67.string().optional()}),z67.object({type:z67.literal("code"),code:z67.string(),lang:z67.string().optional(),caption:z67.string().optional()}),z67.object({type:z67.literal("risk"),level:z67.enum(["warning","error"]),content:z67.array(InlineSchema).max(24)}),z67.object({type:z67.literal("list"),items:z67.array(z67.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z67.object({headline:z67.string(),blocks:z67.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z67.object({summary:EnvDiffSummarySchema,fingerprint:z67.string(),generatedAt:z67.coerce.date(),cached:z67.boolean().optional(),credits:z67.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema2(EnvDiffSummaryResultSchema)}});import{z as z68}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z68.object({date:z68.string(),visitors:z68.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z68.object({key:z68.string(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z68.object({path:z68.string(),pageName:z68.string().nullable().optional(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z68.object({preset:z68.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z68.string(),requestedTo:z68.string(),effectiveFrom:z68.string(),effectiveTo:z68.string(),isRetentionLimited:z68.boolean(),groupBy:z68.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z68.object({date:z68.string(),content:z68.string(),updatedAt:z68.string(),updatedByUserId:z68.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z68.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z68.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z68.number().int().nonnegative(),pageviews:z68.number().int().nonnegative(),botPageviews:z68.number().int().nonnegative(),botVisitors:z68.number().int().nonnegative(),bounceRate:z68.number().min(0).max(100),viewsPerVisit:z68.number().nonnegative(),averageVisitDurationSeconds:z68.number().nonnegative(),visitorsSeries:z68.array(ProjectDailyVisitorsDTOSchema),topPages:z68.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z68.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z68.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z69}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common2();init_create_dto();ProjectInviteDTOSchema=z69.object({id:z69.string(),email:z69.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z69.coerce.date(),createdAt:z69.coerce.date(),inviterUserId:z69.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z69.object({id:z69.string(),token:z69.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z69.object({success:z69.boolean(),projectId:z69.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z70}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z70.object({id:z70.string(),name:z70.string(),image:z70.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z70.object({count:z70.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z70.object({counts:z70.object({signed_up:z70.int(),activated:z70.int()}),credits:z70.object({total:z70.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z70.email(),emailVerified:z70.boolean(),createdAt:z70.coerce.date(),updatedAt:z70.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema2(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema2(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema2(ReferralSummaryCTOSchema)}});import{z as z71}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common2();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z71.object({id:z71.string(),principalType:ProjectPrincipalTypeSchema,principalId:z71.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z71.coerce.date(),expiresAt:z71.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z71.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z71.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z71.record(z71.string(),z71.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z71.object({access:z71.array(ProjectAccessItemDTOSchema),invites:z71.array(ProjectInviteDTOSchema),organization:z71.object({name:z71.string().nullable(),logo:z71.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema2(z71.object({success:z71.boolean()})),InviteAcceptResponseSchema=createResponseSchema2(z71.object({success:z71.boolean(),projectId:z71.uuid()}))}});import{z as z72}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common2();init_create_dto();PublicationStateDTOSchema=z72.object({publicationStatus:PublicationStatusSchema,appUrl:z72.string().nullable(),lastPublishedAt:z72.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z73}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z73.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z73.object({branch:BranchSchema,revision:z73.string().min(1).max(64).nullable(),generation:z73.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z73.url().nullable()})}});import{z as z74}from"zod";var 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=z74.object({code:z74.literal("PREVIEW_UPGRADE_REQUIRED"),message:z74.string(),currentVersion:z74.number().int().positive(),targetVersion:z74.literal(4)}),PreviewBridgePackageSchema=z74.object({name:z74.string().min(1),version:z74.string().min(1)}),PreviewBridgeCapabilitySchema=z74.object({integrated:z74.boolean(),packages:z74.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z74.object({url:z74.url(),expiresAt:z74.iso.datetime().nullable(),source:z74.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema2(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z74.object({name:z74.string().min(1),locator:z74.string().min(1).optional(),source:z74.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z74.object({kind:z74.literal("dependency_build_scripts_blocked"),packageManager:z74.enum(["pnpm","yarn","bun"]),packages:z74.array(z74.string()),targets:z74.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z74.string(),approvalKey:z74.string(),command:z74.string().optional(),approval:z74.object({id:z74.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z74.object({code:z74.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z74.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z74.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z74.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z74.object({message:z74.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z74.number().int().optional().catch(void 0),logTail:z74.array(z74.string()).optional().catch(void 0),logTailTruncated:z74.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z74.object({approvalId:z74.uuid()}),PreviewInstallPolicyApprovalEventSchema=z74.discriminatedUnion("type",[z74.object({type:z74.literal("progress"),step:z74.enum(["approval","install","restart","readiness"]),message:z74.string()}),z74.object({type:z74.literal("approved")}),z74.object({type:z74.literal("complete")}),z74.object({type:z74.literal("error"),code:z74.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z74.string()})])}});import{z as z75}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common2();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z75.string(),slug:z75.string().nullable(),logo:z75.string().nullable(),metadata:z75.record(z75.string(),z75.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z75.object({id:z75.string(),name:z75.string(),email:z75.email(),image:z75.string().nullable()}),OrganizationMemberDTOSchema=z75.object({id:z75.string(),userId:z75.string(),organizationId:z75.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z75.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z76}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,AutomaticSpendStopDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,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=z76.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z76.object({reason:CancellationReasonCodeSchema,details:z76.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z76.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z76.object({offerVersion:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),renewsOn:z76.string()}),PlanMigrationPreviewDTOSchema=z76.object({currency:z76.string().trim().min(1),unusedPremiumCreditAmount:z76.number().int().nonnegative(),amountDueNow:z76.number().int().nonnegative(),startsAt:z76.string(),renewsAt:z76.string(),nextRenewalAmount:z76.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z76.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z76.object({id:z76.string(),organizationId:z76.string(),legacySubscriptionId:z76.string(),offeredPlanCode:z76.string(),offeredPlanName:z76.string(),offeredPriceAmount:z76.number(),offeredCurrency:z76.string(),offerVersion:z76.string(),state:PlanMigrationStateSchema,checkoutToken:z76.string().nullable(),deadlineAt:z76.string(),transitions:z76.array(z76.object({event:z76.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z76.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z76.object({included:z76.number().optional(),unitPrice:z76.number().optional(),dailyCap:z76.number().nullable().optional()}),EntitlementsDTOSchema=z76.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z76.object({retentionDays:z76.number().int().positive(),canUseExtendedDateRanges:z76.boolean()}).optional(),history:z76.object({retentionDays:z76.number().int().positive()}).optional(),members:z76.object({canInvite:z76.boolean(),maxMembers:z76.number().int().positive().nullable()}).optional(),projects:z76.object({maxProjects:z76.number().int().positive().nullable()}).optional(),domains:z76.object({canUseCustomDomains:z76.boolean(),maxDomains:z76.number().int().nonnegative().nullable()}).optional(),media_storage:z76.object({limitBytes:z76.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z76.object({usedBytes:z76.number().int().nonnegative().nullable(),limitBytes:z76.number().int().nonnegative().nullable(),state:z76.enum(["ready","unavailable"]),measuredAt:z76.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z76.object({toPlanCode:TemplateCodeSchema,effectiveAt:z76.string(),scheduledAt:z76.string().nullable()}),AutomaticSpendStopDTOSchema=z76.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z76.string(),spendStopped:z76.boolean(),settlementEndsAt:z76.string()}),HostingOverageStatusDTOSchema=z76.object({state:z76.enum(["ready","unavailable"]),planCode:z76.string(),overageAvailable:z76.boolean(),overageEnabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().nullable(),agentRuntimeEnabled:z76.boolean(),agentRuntimeAvailable:z76.boolean(),periodStart:z76.iso.datetime().nullable(),periodEnd:z76.iso.datetime().nullable(),usedBytes:z76.number().nonnegative().nullable(),includedBytes:z76.number().nonnegative().nullable(),overageBytes:z76.number().nonnegative(),currentOverageAmountMicros:z76.number().nonnegative().nullable(),agentRuntimeAmountMicros:z76.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z76.number().nonnegative().nullable(),currency:z76.string().nullable(),status:z76.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z76.object({enabled:z76.boolean(),monthlyCapUsd:z76.number().int().positive().max(1e6).optional(),agentRuntimeEnabled:z76.boolean().optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z76.object({id:z76.string(),external_id:z76.string(),customerId:z76.string(),planId:z76.string(),planCode:z76.union([TemplateCodeSchema,z76.literal("Unknown")]),currentPeriod:z76.object({start:z76.string(),end:z76.string().nullable()}),cancelAt:z76.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z76.string(),nextPaymentAt:z76.string().nullable(),baseAmount:z76.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z76.object({totalCap:z76.number(),dailyCap:z76.number(),usedTotal:z76.number()}),CreditBalanceDTOSchema=z76.object({total:z76.number(),base:z76.number(),dailyBase:z76.number(),purchases:z76.number(),awards:z76.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z76.object({total:z76.number(),nearLimit:z76.boolean(),canChat:z76.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z76.object({dailyFreeAvailable:z76.number(),monthlyAvailable:z76.number(),purchasedAvailable:z76.number(),awardedAvailable:z76.number()}),ProjectDailyCreditAllowanceDTOSchema=z76.object({periodCap:z76.number(),dailyGrant:z76.number(),usedThisPeriod:z76.number(),remainingThisPeriod:z76.number()}),ProjectCreditBalanceDTOSchema=z76.object({projectId:z76.uuid(),organizationId:z76.string(),balance:z76.object({totalAvailable:z76.number(),nearLimit:z76.boolean(),canUseAi:z76.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z76.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z76.enum(["ok","near_limit","exhausted"]),AgentRuntimeOverageRefusalSchema=z76.enum(["plan_unknown","plan_cannot_fund","pending_plan_exit","consent_missing"]),AgentRuntimeOverageDTOSchema=z76.object({available:z76.boolean(),enabled:z76.boolean(),status:z76.enum(["included","paid","paused"]),pauseReason:AgentRuntimeOverageRefusalSchema.nullable(),rateUsdPerHour:z76.number().nonnegative().nullable(),monthlyCapUsd:z76.number().positive().nullable(),consentedAt:z76.coerce.date().nullable(),billableMs:z76.number().int().nonnegative(),paidRemainingMs:z76.number().int().nonnegative(),projectedAmountUsd:z76.number().nonnegative().nullable()}),AgentRuntimeUsageDTOSchema=z76.object({planCode:z76.enum(["Free","PAYG","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z76.object({source:z76.enum(["cached_subscription","free_fallback"]),settledMs:z76.number().int().nonnegative(),activeMs:z76.number().int().nonnegative(),reservedMs:z76.number().int().nonnegative().optional(),includedMs:z76.number().int().positive(),remainingMs:z76.number().int().nonnegative(),extraMs:z76.number().int().nonnegative(),resetsAt:z76.coerce.date()}),overage:AgentRuntimeOverageDTOSchema}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().nonnegative(),refillAmountUsd:z76.number().nonnegative()}),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().nonnegative().nullable(),refillAmountUsd:z76.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z76.discriminatedUnion("enabled",[z76.object({enabled:z76.literal(!0),thresholdUsd:z76.number().min(.01).multipleOf(.01),refillAmountUsd:z76.number().min(.01).multipleOf(.01),expectedRateToken:z76.string().trim().min(1).max(40)}).strict(),z76.object({enabled:z76.literal(!1),thresholdUsd:z76.number().min(.01).multipleOf(.01),expectedRateToken:z76.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z76.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z76.object({planCode:z76.union([TemplateCodeSchema,z76.literal("Unknown")]).nullable(),canPurchase:z76.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z76.number().int().positive(),minAmountUsd:z76.number().positive(),maxAmountUsd:z76.number().positive(),rateToken:z76.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z76.object({amountUsd:z76.number(),idempotencyKey:z76.string().trim().min(8).max(120),expectedRateToken:z76.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z76.object({invoiceId:z76.string(),newBalance:z76.int(),creditCount:z76.int(),amountUsd:z76.number(),creditsPerDollar:z76.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z76.object({url:z76.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z76.object({id:z76.string(),number:z76.string().nullable(),status:z76.string(),amountDue:z76.int(),currency:z76.string(),issuedAt:z76.string().nullable(),hostedInvoiceUrl:z76.string().nullable()}),PaymentRecoveryDTOSchema=z76.discriminatedUnion("status",[z76.object({status:z76.literal("eligible"),checkedAt:z76.string()}),z76.object({status:z76.literal("recovery_required"),checkedAt:z76.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z76.int().min(1)}),z76.object({status:z76.literal("unavailable"),checkedAt:z76.string(),reason:z76.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 z77}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z77.object({brand:z77.string(),last4:z77.string(),exp:z77.string(),isDefault:z77.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z78}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema2,EntryDTO,PaginatedEntriesDTOSchema2,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema2,EntryListResponseSchema,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema2,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema2,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema2,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common2();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z78.string().superRefine((path52,ctx)=>{let segments=path52.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z78.object({type:z78.literal("renameField"),contentType:z78.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z78.object({enabled:z78.boolean()}).strict(),ContentFieldGroupSchema=z78.object({id:z78.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z78.string().min(1).max(255),default:z78.boolean().optional()}).strict(),ContentTypeDTOSchema=z78.object({id:z78.string(),name:z78.string(),label:z78.string(),isSingleton:z78.boolean(),i18n:ContentTypeI18nSchema,groups:z78.array(ContentFieldGroupSchema).default([]),fields:z78.record(z78.string(),FieldDefinitionSchema),createdAt:z78.string(),updatedAt:z78.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z78.object({contentTypes:z78.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema2=z78.object({id:z78.string(),entryId:z78.string(),documentId:z78.string(),slug:z78.string(),locale:z78.string().optional(),createdAt:z78.string(),updatedAt:z78.string(),__fimo:z78.object({contentType:z78.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema2),PaginatedEntriesDTOSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({limit:z78.number(),offset:z78.number(),total:z78.number(),hasMore:z78.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema2),EntryCountDTOSchema=z78.object({contentType:z78.string(),count:z78.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z78.object({counts:z78.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z78.object({count:z78.number().int().nonnegative(),sourceLocale:z78.string(),targetLocale:z78.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema2(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema2(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema2(z78.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema2(SchemaDTOSchema),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),EntryListResponseSchema=createResponseSchema2(z78.array(EntryDTOSchema2)),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z78.union([z78.string(),z78.number(),z78.boolean(),z78.null()]),entryWhereOperatorSchema2=z78.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z78.array(entryWhereScalarSchema2).optional(),$nin:z78.array(entryWhereScalarSchema2).optional(),$contains:z78.string().optional(),$startsWith:z78.string().optional(),$null:z78.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z78.record(z78.string(),z78.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z78.object({data:z78.record(z78.string(),z78.unknown()),locale:z78.string().min(1).optional(),documentId:z78.uuid().optional()}),entryIdsSchema=z78.array(z78.uuid()).min(1).max(MAX_BULK_ENTRIES2),EntrySqlQueryRequestSchema=z78.object({sql:z78.string().min(1)}),BulkCreateEntriesRequestSchema=z78.object({entries:z78.array(EntryMutationBodySchema2).min(1).max(MAX_BULK_ENTRIES2)}),BulkUpdateEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,body:EntryMutationBodySchema2}),z78.object({where:EntryWhereSchema2,body:EntryMutationBodySchema2}),z78.object({updates:z78.array(z78.object({id:z78.uuid(),body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),BulkDeleteEntriesRequestSchema=z78.union([z78.object({ids:entryIdsSchema,locale:z78.string().min(1).optional()}),z78.object({where:EntryWhereSchema2,locale:z78.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z78.object({data:z78.array(z78.record(z78.string(),z78.unknown())),meta:z78.object({rowCount:z78.number().int().nonnegative(),truncated:z78.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({created:z78.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema2),BulkUpdateEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({updated:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema2),BulkDeleteEntriesResponseSchema2=z78.object({data:z78.array(EntryDTOSchema2),meta:z78.object({deleted:z78.number().int().nonnegative(),missing:z78.array(z78.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema2)}});import{z as z79}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z79.object({index:z79.number().int().nonnegative(),contentType:z79.string(),field:z79.string(),value:z79.string(),against:z79.enum(["stored","batch"]),ownerDocumentId:z79.uuid().optional(),ownerIndex:z79.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z79.object({code:z79.literal("unique_conflict"),message:z79.string(),conflicts:z79.array(UniqueConflictSchema),truncated:z79.boolean().optional()})}});import{z as z80}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z80.object({kind:z80.literal("unique_conflict"),contentType:z80.string(),field:z80.string(),value:z80.string(),documentCount:z80.number().int().positive(),documentIds:z80.array(z80.uuid()),documentIdsTruncated:z80.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z80.object({code:z80.literal("schema_transition_rejected"),message:z80.string(),issues:z80.array(SchemaTransitionIssueSchema),truncated:z80.boolean().optional()})}});import{z as z81}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common2();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z81.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z81.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z81.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z81.object({field:CmsFieldNameSchema,direction:z81.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z81.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z81.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z81.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z81.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z81.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema2(CmsDisplayDefaultsDTOSchema)}});import{z as z82}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z82.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z83}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z83.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z83.object({event:ClientTrackedEventSchema,properties:z83.record(z83.string(),z83.unknown()).default({})})}});import{z as z84}from"zod";var AssetPathItemSchema,AssetDTOSchema2,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema2,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common2();init_create_dto();init_response();AssetPathItemSchema=z84.object({id:z84.string(),name:z84.string()}),AssetDTOSchema2=z84.object({id:z84.string(),name:z84.string(),type:AssetTypeSchema,originalFileName:z84.string().nullable(),parentId:z84.string().nullable(),mimeType:z84.string().nullable(),fileSize:z84.number().nullable(),url:z84.string().nullable(),storageKey:z84.string().nullable(),createdAt:z84.string(),updatedAt:z84.string(),altText:z84.string().nullable().optional(),caption:z84.string().nullable().optional(),aiCaption:z84.string().nullable().optional(),aiAltText:z84.string().nullable().optional(),aiTags:z84.array(z84.string()).nullable().optional(),aiPrimaryColor:z84.string().nullable().optional(),aiProcessingStatus:z84.string().nullable().optional(),width:z84.number().nullable().optional(),height:z84.number().nullable().optional(),path:z84.array(AssetPathItemSchema).optional(),hasChildren:z84.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema2),AssetTreeNodeDTOSchema=AssetDTOSchema2.extend({children:z84.lazy(()=>z84.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetListResponseSchema=createResponseSchema2(z84.array(AssetDTOSchema2)),MediaStorageLimitErrorSchema=z84.object({error:z84.string(),code:z84.literal("media_storage_limit_exceeded"),usedBytes:z84.number().int().nonnegative(),limitBytes:z84.number().int().positive(),incomingBytes:z84.number().int().nonnegative()}),AssetReferenceScopeSchema=z84.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z84.object({assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z84.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z84.object({totalFiles:z84.number().int().nonnegative(),checkedFiles:z84.number().int().nonnegative(),limit:z84.number().int().positive()}),AssetReferenceFindingDTOSchema=z84.object({assetId:z84.uuid(),entryId:z84.string(),documentId:z84.string(),contentType:z84.string(),locale:z84.string().nullable(),slug:z84.string(),fieldPath:z84.string()}),AssetReferenceScopeResultDTOSchema=z84.object({scope:AssetReferenceScopeSchema,label:z84.string(),state:z84.enum(["available","not-published","failed"]),coverage:z84.enum(["complete","partial","failed"]),referenceCount:z84.number().int().nonnegative().optional(),codeReferenceCount:z84.number().int().nonnegative().optional(),referencedAssetIds:z84.array(z84.uuid()).optional(),references:z84.array(AssetReferenceFindingDTOSchema),reason:z84.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z84.discriminatedUnion("type",[z84.object({type:z84.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z84.object({type:z84.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z84.object({type:z84.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z84.object({replacementAssetId:z84.uuid()}),AssetReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),entriesChanged:z84.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema2(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z84.object({referencesReplaced:z84.number().int().nonnegative(),filesChanged:z84.number().int().nonnegative(),commitSha:z84.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z84.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z84.object({error:z84.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z84.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z84.object({intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z84.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z84.object({id:z84.uuid(),intent:AssetRemovalIntentSchema,assetIds:z84.array(z84.uuid()),replacementAssetId:z84.uuid().nullable(),expiresAt:z84.iso.datetime(),undoable:z84.boolean(),requestedByMe:z84.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z84.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z84.object({error:z84.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z85}from"zod";var TranslationDTOSchema2,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema2=z85.object({key:z85.string(),value:z85.string().optional(),defaultValue:z85.string(),locale:z85.string()}),TranslationDTO=createDTO(TranslationDTOSchema2)}});import{z as z86}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z86.object({id:z86.string(),name:z86.string(),type:z86.enum(["file","folder"]),path:z86.string(),children:z86.lazy(()=>z86.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z86.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z86.object({path:z86.string(),exists:z86.boolean(),type:z86.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema2(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema2(DocumentPathDTOSchema)}});import{z as z87}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema2,FormUpdateSchema2,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z87.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z87.object({minLength:z87.number().optional(),maxLength:z87.number().optional(),min:z87.number().optional(),max:z87.number().optional(),pattern:z87.string().optional(),maxFileSize:z87.number().optional(),accept:z87.array(z87.string()).optional()}),FormFieldSchema=z87.object({type:FormFieldTypeSchema,label:z87.string(),placeholder:z87.string().optional(),required:z87.boolean().optional(),defaultValue:z87.string().optional(),options:z87.array(z87.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z87.record(z87.string(),FormFieldSchema),FormContentSchema2=z87.object({name:z87.string().min(1).max(255),label:z87.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z88}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z88.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z88.object({items:z88.array(ProjectMessagePublicDTOSchema),nextCursor:z88.string().nullable()}),ChatLiveTurnDTOSchema=z88.object({invocationId:z88.string(),step:z88.enum(["preparing","working","compacting","merging"]),startedAt:z88.string(),continuesInvocationId:z88.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z88.object({threadId:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z88.object({id:z88.string(),role:z88.enum(["user","assistant"]),parts:z88.array(z88.unknown()),metadata:z88.record(z88.string(),z88.unknown()).nullable(),versionId:z88.string().nullable().optional(),createdAt:z88.date().transform(value=>value.toISOString()),providerMessageId:z88.string().nullable().optional(),invocationId:z88.string().nullable().optional(),invocationStatus:z88.string().nullable().optional(),invocationTerminalReason:z88.string().nullable().optional()}),ChatAttentionDTOSchema=z88.object({type:z88.literal("merge_conflict"),merge:z88.object({mergeId:z88.string().uuid(),projectId:z88.string(),fromBranch:z88.string(),toBranch:z88.string()}),publishAfterMerge:z88.boolean()}),ChatThreadMessagesPageDTOSchema=z88.object({threadId:z88.string().nullable(),title:z88.string().nullable(),messages:z88.array(ChatThreadMessageDTOSchema),nextCursor:z88.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z88.object({kind:z88.literal("replay"),threadId:z88.string(),userMessageId:z88.string()}),ChatQueuedOutcomeDTOSchema=z88.object({kind:z88.literal("queued"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string()}),ChatBusyOutcomeDTOSchema=z88.object({kind:z88.literal("busy"),threadId:z88.string(),userMessageId:z88.string(),blockingRootId:z88.string().optional()}),ChatRefusedOutcomeDTOSchema=z88.object({kind:z88.literal("refused"),threadId:z88.string(),userMessageId:z88.string(),refusedInvocationId:z88.string(),terminalReason:z88.string()}),ChatNonStreamingOutcomeDTOSchema=z88.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z88.object({success:z88.boolean(),deletedCount:z88.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema2(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema2(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema2(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z88.object({code:z88.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z88.string()})}});import{z as z89}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common2();init_create_dto();init_response();UploadResultDTOSchema=z89.object({url:z89.string().url(),key:z89.string(),size:z89.number(),contentType:z89.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema2(UploadResultDTOSchema)}});import{z as z90}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z90.object({canAccess:z90.boolean(),permissions:z90.record(z90.string(),z90.boolean()),role:z90.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema2(ServicePermissionsDTOSchema)}});import{z as z91}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z91.string().trim().default(""),sort:z91.enum(["recent","name","relevance"]).default("recent"),category:z91.string().optional()})}});import{z as z92}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common2();init_create_dto();init_response();DomainStatusSchema=z92.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z92.enum(["fimo","external"]),PaymentStatusSchema=z92.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z92.object({id:z92.string().uuid(),domain:z92.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z92.boolean(),price:z92.number().int().nullable(),renewalPrice:z92.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z92.string().nullable(),failureReason:z92.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z92.object({domain:z92.string(),available:z92.boolean(),premium:z92.boolean(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),purchaseType:z92.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z92.object({domain:z92.string(),price:z92.number().nullable(),renewalPrice:z92.number().nullable(),premium:z92.boolean(),allowedYears:z92.array(z92.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z92.object({firstName:z92.string().max(100),lastName:z92.string().max(100),companyName:z92.string().max(100).optional(),address1:z92.string().max(255),address2:z92.string().max(255).optional(),city:z92.string().max(100),state:z92.string().max(100),zip:z92.string().max(20),country:z92.string().max(2),phone:z92.string().max(30),email:z92.union([z92.string().email().max(255),z92.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z92.object({firstName:z92.string().min(1).max(100),lastName:z92.string().min(1).max(100),companyName:z92.string().max(100).optional(),address1:z92.string().min(1).max(255),address2:z92.string().max(255).optional(),city:z92.string().min(1).max(100),state:z92.string().min(1).max(100),zip:z92.string().min(1).max(20),country:z92.string().min(1).max(2),phone:z92.string().min(1).max(30),email:z92.string().email().max(255)}),SearchDomainsRequestSchema=z92.object({keyword:z92.string().min(1).max(100),tldFilter:z92.array(z92.string()).optional()}),CheckAvailabilityRequestSchema=z92.object({domains:z92.array(z92.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z92.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z92.object({domain:DomainNameSchema,years:z92.number().int().min(1).max(10).optional().default(3),autoRenew:z92.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z92.object({autoRenew:z92.boolean().optional()}),RenewDomainRequestSchema=z92.object({years:z92.number().int().min(1).max(10).optional().default(1),autoRenew:z92.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema2(DomainDTOSchema),DomainListResponseSchema=createResponseSchema2(z92.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema2(z92.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema2(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema2(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z92.object({verified:z92.boolean(),email:z92.string().nullable(),verifyBy:z92.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema2(ContactVerificationStatusSchema)}});import{z as z93}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common2();init_create_dto();init_response();ProjectDomainStatusSchema=z93.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z93.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z93.object({txtName:z93.string().nullable().optional(),txtValue:z93.string().nullable().optional(),httpUrl:z93.string().nullable().optional(),httpBody:z93.string().nullable().optional(),cname:z93.string().nullable().optional(),cnameTarget:z93.string().nullable().optional()}),SSLValidationErrorSchema=z93.object({message:z93.string()}),OwnershipVerificationSchema=z93.object({type:z93.string(),name:z93.string(),value:z93.string()}),ProjectDomainSSLDTOSchema=z93.object({status:z93.string(),method:z93.string().nullable(),type:z93.string().nullable(),validationRecords:z93.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z93.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z93.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z93.enum(["subdomain","apex"]),RedirectConfigSchema=z93.object({type:z93.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z93.string()}).nullable().optional(),ProjectDomainDTOSchema=z93.object({id:z93.string(),hostname:z93.string(),status:z93.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z93.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z93.string(),scdCnameTarget:z93.string().optional(),apexTargets:z93.array(z93.string()),dnsAutoConfigured:z93.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z93.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema2(z93.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema2(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z93.object({hostname:z93.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z93.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z93.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema2(z93.object({available:z93.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema2(z93.object({success:z93.boolean(),hostname:z93.string()}))}});import{z as z94}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema2(z94.object({available:z94.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z94.object({slug:z94.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z94.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema2(z94.object({subdomain:z94.string(),subdomainUpdatedAt:z94.coerce.date()})),SubdomainSuggestionsQuerySchema=z94.object({base:z94.string().max(100).optional(),max:z94.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema2(z94.object({suggestions:z94.array(z94.string())}))}});import{z as z95}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z95.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z95.object({code:ProjectTransferBlockerCodeSchema,message:z95.string(),count:z95.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z95.object({targetOrganizationId:z95.string().min(1)}),ProjectTransferResultDTO=createDTO(z95.object({projectId:z95.string(),sourceOrganizationId:z95.string(),targetOrganizationId:z95.string(),movedThreads:z95.number().int().nonnegative(),revokedInvites:z95.number().int().nonnegative(),revokedGrants:z95.number().int().nonnegative(),preservedGrants:z95.number().int().nonnegative(),warnings:z95.array(z95.string())}))}});import{z as z96}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema2,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema2,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z96.object({translated:z96.number().int().nonnegative(),total:z96.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z96.object({locale:z96.string(),isDefault:z96.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z96.object({defaultLocale:z96.string(),locales:z96.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema2=createResponseSchema2(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z96.object({locale:z96.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z96.object({locale:z96.string().min(1).max(40)}),ProjectLocaleMutationSchema=z96.object({locale:z96.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema2=createResponseSchema2(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z96.object({locale:z96.string(),entriesDeleted:z96.number().int().nonnegative(),labelsDeleted:z96.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema2=createResponseSchema2(RemoveProjectLocaleSchema)}});import{z as z97}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z97.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z97.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z97.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z97.number(),credits:z97.number().optional(),billingMode:z97.enum(["fimo-credits","provider-account"]).optional(),confidence:z97.enum(["exact","estimated","metered"]),basis:z97.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z98}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema2,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z98.object({options:z98.record(z98.string(),z98.unknown()),name:z98.string().optional(),parentId:z98.string().nullable().optional(),altText:z98.string().optional(),caption:z98.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z98.string().min(1).optional(),model:z98.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z98.object({jobId:z98.string(),status:z98.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z98.string().nullable().optional(),credits:z98.number().optional(),costUsd:z98.number().optional(),billingMode:z98.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema2=createResponseSchema2(GenerateResponseDataSchema),GenerateErrorSchema=z98.object({error:z98.string(),code:z98.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z98.array(GenerationTaskIdSchema).optional(),availableModels:z98.array(z98.string()).optional(),issues:z98.array(z98.unknown()).optional()})}});import{z as z99}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z99.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z99.object({name:z99.string(),key:z99.string(),description:z99.string(),type:FlagTypeSchema,required:z99.boolean(),defaultValue:z99.unknown().optional(),enumValues:z99.array(z99.string()).optional(),isArray:z99.boolean()}),AssetModelPriceSchema=z99.object({unitPrice:z99.number(),unit:z99.string(),confidence:z99.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z99.object({id:z99.string(),shortName:z99.string(),provider:z99.string(),source:z99.string(),modality:z99.enum(["image","video","audio"]),tags:z99.array(z99.string()),displayName:z99.string(),description:z99.string(),flags:z99.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z99.object({model:z99.string(),costUsd:z99.number(),credits:z99.number(),billingMode:z99.enum(["fimo-credits","provider-account"]),confidence:z99.enum(["exact","estimated","metered"]),basis:z99.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z100}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z100.object({tourId:z100.string(),version:z100.string(),status:z100.string(),completedAt:z100.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema2(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema2(z100.array(UserTourDTOSchema))}});import{z as z101}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z101.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z101.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z101.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z101.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z101.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z101.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z101.enum(["user","agent","system"]),SupportReportTagSchema=z101.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z101.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z101.object({organization:z101.object({id:z101.string().trim().min(1).max(255),name:z101.string().trim().max(240).optional()}),project:z101.object({id:z101.uuid(),name:z101.string().trim().max(240).optional(),createdAt:z101.coerce.date().optional()}).optional(),environment:z101.string().trim().max(255).optional(),clientVersion:z101.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z101.object({message:z101.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z101.string().trim().max(200).optional(),limit:z101.coerce.number().int().min(1).max(100).default(50),offset:z101.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z101.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z101.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z101.uuid().nullable().optional(),note:z101.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z101.object({message:z101.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z101.object({kind:SupportReportLinkKindSchema,label:z101.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z101.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z101.object({kind:SupportReportActorKindSchema,id:z101.string().nullable(),name:z101.string().nullable()}),SupportReportLinkDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportLinkKindSchema,label:z101.string(),url:SupportReportHttpUrlSchema,externalId:z101.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z101.object({id:z101.uuid(),kind:SupportReportEventKindSchema,body:z101.string().nullable(),metadata:z101.record(z101.string(),z101.unknown()),actor:SupportReportActorDTOSchema,createdAt:z101.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z101.object({id:z101.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z101.array(z101.string()),source:SupportReportSourceSchema,message:z101.string(),reporter:z101.object({id:z101.string().nullable(),name:z101.string().nullable(),email:z101.string().nullable()}),organization:z101.object({id:z101.string().nullable(),name:z101.string()}),project:z101.object({id:z101.uuid().nullable(),name:z101.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z101.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z101.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z101.string().nullable(),deliveredAt:z101.coerce.date().nullable()}).nullable(),duplicateOfReportId:z101.uuid().nullable(),resolvedAt:z101.coerce.date().nullable(),createdAt:z101.coerce.date(),updatedAt:z101.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z101.string().nullable(),clientVersion:z101.string().nullable(),links:z101.array(SupportReportLinkDTOSchema),events:z101.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z101.object({reports:z101.array(SupportReportSummaryDTOSchema),total:z101.number().int().nonnegative(),statusCounts:z101.object({new:z101.number().int().nonnegative(),in_progress:z101.number().int().nonnegative(),waiting:z101.number().int().nonnegative(),resolved:z101.number().int().nonnegative(),duplicate:z101.number().int().nonnegative(),irrelevant:z101.number().int().nonnegative(),ignored:z101.number().int().nonnegative()}),limit:z101.number().int().positive(),offset:z101.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z101.object({id:z101.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z101.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z102}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z102.iso.datetime({offset:!0}).pipe(z102.coerce.date()),OpsRecentChatInputSchema=z102.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z102.string().trim().min(1).max(255).optional(),limit:z102.coerce.number().int().min(1).max(200).default(100),cursor:z102.string().trim().min(1).max(2e3).optional(),slim:z102.boolean().default(!0),reason:z102.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z102.object({id:z102.string(),threadId:z102.string(),providerMessageId:z102.string().nullable(),invocationId:z102.string().nullable(),env:z102.string().nullable(),role:z102.string(),parts:z102.array(z102.record(z102.string(),z102.unknown())),metadata:z102.object({status:z102.string().optional(),traceUrl:z102.string().optional(),externalFileChanges:z102.array(z102.unknown()).optional()}),stats:z102.object({toolCount:z102.number().int().nonnegative(),failedToolCount:z102.number().int().nonnegative()}),createdAt:z102.iso.datetime({offset:!0}),project:z102.object({id:z102.string(),name:z102.string(),displayName:z102.string().nullable(),organizationId:z102.string().nullable()})}),OpsRecentChatResponseSchema=z102.object({target:z102.object({backendProfile:OpsBackendProfileSchema,projectEnv:z102.string().nullable()}),window:z102.object({from:z102.iso.datetime({offset:!0}),to:z102.iso.datetime({offset:!0})}),messages:z102.object({items:z102.array(OpsRecentChatMessageSchema),nextCursor:z102.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z103}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z103.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z103.object({backendProfile:OpsBackendProfileSchema,provider:z103.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z103.literal(!1),reason:z103.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z104}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z104.object({packageManager:z104.string().trim().min(1).max(200).nullable(),trackedLockfiles:z104.array(z104.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z104.string().trim().min(1)}),OpsProjectPackageManagerSchema=z104.object({target:z104.object({backendProfile:OpsBackendProfileSchema,projectId:z104.uuid(),projectEnv:z104.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z105}from"zod";var OPS_AGENT_BRANCH_DISCARD_LIMIT,OpsAgentBranchAllowlistSchema,OpsAgentBranchRecoveredOwnerSchema,OpsAgentBranchDiscardPlanInputSchema,OpsAgentBranchDiscardApplyInputSchema,OPS_AGENT_BRANCH_DISCARD_BLOCKERS,OpsAgentBranchDiscardBlockerSchema,init_ops_agent_branch_discard_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-branch-discard.dto.js"(){"use strict";init_env();OPS_AGENT_BRANCH_DISCARD_LIMIT=25,OpsAgentBranchAllowlistSchema=z105.array(BranchSchema).min(1,"name at least one Branch to discard").max(OPS_AGENT_BRANCH_DISCARD_LIMIT).refine(branches=>new Set(branches).size===branches.length,{error:"the Branch allowlist must not repeat a Branch"}),OpsAgentBranchRecoveredOwnerSchema=z105.object({branch:BranchSchema,sessionId:z105.uuid()}),OpsAgentBranchDiscardPlanInputSchema=z105.object({branches:OpsAgentBranchAllowlistSchema,reason:z105.string().trim().min(1).max(1e3),recoveredOwners:z105.array(OpsAgentBranchRecoveredOwnerSchema).max(OPS_AGENT_BRANCH_DISCARD_LIMIT).optional()}).refine(input=>(input.recoveredOwners??[]).every(owner=>input.branches.includes(owner.branch)),{error:"every recovered owner must name a Branch from the allowlist",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.branch)).size===owners.length},{error:"recovered owners must not repeat a Branch",path:["recoveredOwners"]}).refine(input=>{let owners=input.recoveredOwners??[];return new Set(owners.map(owner=>owner.sessionId)).size===owners.length},{error:"recovered owners must not repeat a session",path:["recoveredOwners"]}),OpsAgentBranchDiscardApplyInputSchema=OpsAgentBranchDiscardPlanInputSchema.safeExtend({planHash:z105.string().trim().length(64)}),OPS_AGENT_BRANCH_DISCARD_BLOCKERS=["branch_not_found","not_agent_session_branch","branch_not_active","production_branch","default_branch","production_source_branch","owner_session_missing","not_project_agent_run","open_merge","live_mcp_session","live_owner","has_descendants","recovery_direct_owner_present","recovery_session_not_found","recovery_session_not_project_agent_run","recovery_session_not_terminal","recovery_session_already_bound"],OpsAgentBranchDiscardBlockerSchema=z105.enum(OPS_AGENT_BRANCH_DISCARD_BLOCKERS)}});import{z as z106}from"zod";function createAgentRunWebhookEventDataSchema(status){return z106.object({run:z106.object({id:z106.string(),agentName:z106.string(),trigger:z106.string(),status:z106.literal(status),startedAt:z106.string().nullable(),finishedAt:z106.string().nullable(),reason:z106.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common2();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z106.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z106.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z106.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z106.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z106.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z106.object({reason:WebhookEntryChangeReasonSchema,operationId:z106.string().optional(),batch:z106.object({index:z106.number().int().positive(),total:z106.number().int().positive()}).optional(),changes:z106.array(z106.object({action:WebhookEntryChangeActionSchema,contentType:z106.string(),id:z106.string(),documentId:z106.string(),locale:z106.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z106.object({form:z106.object({id:z106.string(),label:z106.string()}),submission:z106.object({id:z106.string(),data:z106.record(z106.string(),z106.unknown()),submittedAt:z106.string()})}),PublishStartedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("publishing"),startedAt:z106.string()})}),PublishSucceededWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("published"),url:z106.string(),publishedAt:z106.string(),firstPublish:z106.boolean()})}),PublishFailedWebhookEventDataSchema=z106.object({publication:z106.object({status:z106.literal("failed"),reason:z106.string()})}),PublishUnpublishedWebhookEventDataSchema=z106.object({publication:z106.object({previousUrl:z106.string(),unpublishedAt:z106.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z106.object({review:z106.object({runId:z106.string(),agentName:z106.string(),reason:z106.string()}),source:z106.object({branch:z106.string(),revision:z106.string(),anchorBranch:z106.string()})}),AgentReviewResolvedWebhookEventDataSchema=z106.object({review:z106.object({id:z106.string(),runId:z106.string(),agentName:z106.string(),resolution:z106.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z106.object({report:z106.object({weekStart:z106.string(),weekEnd:z106.string(),pageviews:z106.number(),visitors:z106.number(),previousPageviews:z106.number(),previousVisitors:z106.number()})}),MediaAssetWebhookEventDataSchema=z106.object({id:z106.string().nullable(),name:z106.string().nullable(),type:z106.string(),mimeType:z106.string().nullable(),fileSize:z106.number().nullable()}),MediaUploadedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("updated")}),MediaDeletedWebhookEventDataSchema=z106.object({asset:MediaAssetWebhookEventDataSchema,operation:z106.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z106.object({domain:z106.object({id:z106.string(),hostname:z106.string()})}),LabelChangedWebhookEventDataSchema=z106.object({changes:z106.array(z106.object({action:z106.enum(["created","updated","deleted"]),key:z106.string(),locale:z106.string(),value:z106.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),isDefault:z106.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),previousCode:z106.string()})}),LocaleDeletedWebhookEventDataSchema=z106.object({locale:z106.object({code:z106.string(),entriesDeleted:z106.number().int().nonnegative(),labelsDeleted:z106.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z106.object({environment:z106.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z106.object({merge:z106.object({id:z106.string(),from:BranchSchema,to:BranchSchema,applied:z106.array(z106.object({surface:SurfaceNameSchema,count:z106.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z106.object({branch:z106.object({name:BranchSchema}),version:z106.object({versionId:z106.uuid(),name:z106.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"branch.restored":BranchRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z106.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z106.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z106.discriminatedUnion("source",[z106.object({source:z106.literal("literal"),value:z106.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z106.object({source:z106.literal("secret"),key:z106.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z106.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z106.object({name:z106.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z106.object({name:z106.string(),source:z106.enum(["literal","secret"]),secretKey:z106.string().nullable(),secretPrefix:z106.string().nullable(),configured:z106.literal(!0)}),WebhookFilterSchema=z106.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z106.string().min(1).max(255).optional(),agentName:z106.string().min(1).max(120).optional(),mediaType:z106.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z106.string().min(1).max(255).optional(),locale:z106.string().min(1).max(120).optional()}),JsonValueSchema=z106.lazy(()=>z106.union([z106.string(),z106.number(),z106.boolean(),z106.null(),z106.array(JsonValueSchema),z106.record(z106.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z106.url(),enabled:z106.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z106.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z106.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z106.object({name:z106.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z106.url().optional(),enabled:z106.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z106.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z106.boolean().optional()}),TestProjectWebhookRequestSchema=z106.object({eventType:WebhookEventTypeSchema.optional(),data:z106.record(z106.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z106.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z106.uuid(),name:z106.string(),eventType:WebhookEventTypeSchema,enabled:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z106.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z106.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z106.coerce.date().nullable(),deliveryStats24h:z106.object({succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z106.uuid(),projectId:z106.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z106.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z106.number().int().positive(),test:z106.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z106.number().int().nonnegative(),responseStatus:z106.number().int().nullable(),lastErrorCode:z106.string().nullable(),lastErrorMessage:z106.string().nullable(),payloadAvailable:z106.boolean(),destination:z106.object({host:z106.string(),maskedUrl:z106.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z106.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z106.string().nullable(),qstashMessageId:z106.string().nullable(),deliveredAt:z106.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z106.object({items:z106.array(WebhookDeliveryDTOSchema),pagination:z106.object({page:z106.number().int().positive(),limit:z106.number().int().positive(),total:z106.number().int().nonnegative(),totalPages:z106.number().int().positive(),hasMore:z106.boolean()}),stats:z106.object({total:z106.number().int().nonnegative(),succeeded:z106.number().int().nonnegative(),failed:z106.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z106.object({id:z106.uuid(),deliveryId:z106.uuid(),attempt:z106.number().int().positive(),status:z106.enum(["delivering","succeeded","failed"]),responseStatus:z106.number().int().nullable(),durationMs:z106.number().int().nonnegative(),responseExcerpt:z106.string().nullable(),errorCode:z106.string().nullable(),errorMessage:z106.string().nullable(),createdAt:z106.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema2(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema2(z106.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema2(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema2(z106.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z107}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z107.object({key:z107.literal("fimo-2"),enabled:z107.boolean(),dismissed:z107.boolean().default(!1),interacted:z107.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z108}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common2();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z108.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z108.object({total:z108.number(),base:z108.number(),purchases:z108.number(),awards:z108.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z108.object({id:z108.string(),name:z108.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z108.object({type:z108.string(),brand:z108.string().nullable(),last4:z108.string().nullable(),expirationDate:z108.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z108.object({currency:z108.string(),nextPaymentAmount:z108.number().nullable(),nextPaymentAt:z108.string().nullable(),billingInterval:z108.string().nullable(),totalAmount:z108.number().nullable(),discountAmount:z108.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z108.object({id:z108.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z108.string().nullable(),currentPeriodEndsAt:z108.string().nullable(),renewsAt:z108.string().nullable(),cancelAt:z108.string().nullable(),renewAutomatically:z108.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z108.object({type:z108.enum(["low_balance","critical_balance","approaching_limit"]),message:z108.string(),estimatedPromptsRemaining:z108.number().nullable(),avgCostPerPrompt:z108.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z108.object({monthlyCredits:z108.number().nullable(),usedThisPeriod:z108.number(),remainingThisPeriod:z108.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z108.object({organizationId:z108.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z108.string().nullable(),tenureDays:z108.number().int().nonnegative(),capturedAt:z108.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z108.object({hasSubscription:z108.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z108.number().nullable(),alerts:z108.array(CreditAlertDTOSchema),portalUrl:z108.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z108.object({creditCount:z108.number().int().positive(),expiresAt:z108.string().datetime().nullable().optional(),message:z108.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("free"),amountCents:z108.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z108.literal("purchase"),amountCents:z108.number().int().positive()}),CreditTopupRequestDTOSchema=z108.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z108.object({success:z108.boolean(),transactionId:z108.string().nullable(),newBalance:z108.number(),creditCount:z108.number(),type:z108.enum(["free","purchase"]),invoiceId:z108.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z109}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z109.object({totalCredits:z109.number(),totalCostUsd:z109.number(),totalMessages:z109.number(),avgCostPerMessage:z109.number(),periodStart:z109.string().nullable(),periodEnd:z109.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z109.object({date:z109.string(),credits:z109.number(),costUsd:z109.number(),messages:z109.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z109.object({userId:z109.string(),userName:z109.string().nullable(),userEmail:z109.string().email().nullable(),credits:z109.number(),costUsd:z109.number(),messages:z109.number(),percentage:z109.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z109.object({projectId:z109.string(),projectName:z109.string(),projectDisplayName:z109.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z109.array(UsageByUserForProjectDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z109.object({summary:UsageSummaryDTOSchema,byProject:z109.array(UsageByProjectDTOSchema),byUser:z109.array(UsageByUserDTOSchema),timeline:z109.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z110}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z110.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z110.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z110.object({startDate:z110.string().optional(),endDate:z110.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z110.coerce.number().int().positive().default(1),limit:z110.coerce.number().int().positive().max(100).default(20),sortBy:z110.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z110.string().optional(),activeOnly:z110.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z110.object({totalCredits:z110.number(),totalCostUsd:z110.number(),totalMessages:z110.number(),avgCostPerMessage:z110.number(),avgCreditsPerMessage:z110.number(),periodStart:z110.string(),periodEnd:z110.string(),creditsChange:z110.number().nullable(),costChange:z110.number().nullable(),messagesChange:z110.number().nullable(),unattributedCredits:z110.number(),unattributedCostUsd:z110.number(),unattributedMessages:z110.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z110.object({date:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z110.object({organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number(),projectCount:z110.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z110.object({userId:z110.string(),userName:z110.string().nullable(),userEmail:z110.string().nullable(),userImage:z110.string().nullable(),organizationId:z110.string().nullable(),organizationName:z110.string().nullable(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),projectCount:z110.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z110.object({projectId:z110.string(),projectName:z110.string(),projectDisplayName:z110.string().nullable(),organizationId:z110.string(),organizationName:z110.string(),credits:z110.number(),costUsd:z110.number(),messages:z110.number(),percentage:z110.number(),userCount:z110.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z110.object({id:z110.string(),name:z110.string(),value:z110.number(),percentage:z110.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z110.object({day:z110.number(),hour:z110.number(),value:z110.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z110.object({summary:UsageOverviewSummaryDTOSchema,timeline:z110.array(UsageTimelinePointDTOSchema),topOrganizations:z110.array(OrganizationUsageRowDTOSchema),topUsers:z110.array(UserUsageRowDTOSchema),topProjects:z110.array(ProjectUsageRowDTOSchema),creditDistribution:z110.array(UsageDistributionItemDTOSchema),userDistribution:z110.array(UsageDistributionItemDTOSchema),heatmap:z110.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z110.object({page:z110.number(),limit:z110.number(),totalItems:z110.number(),totalPages:z110.number(),hasMore:z110.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z110.object({organizations:z110.array(OrganizationUsageRowDTOSchema),top:z110.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z110.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z110.object({users:z110.array(ExtendedUserUsageRowDTOSchema),top:z110.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z110.object({projects:z110.array(ExtendedProjectUsageRowDTOSchema),top:z110.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z110.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z110.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z110.object({credits:z110.number(),costUsd:z110.number(),messages:z110.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),createdAt:z110.string(),memberCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z110.object({id:z110.string(),name:z110.string().nullable(),email:z110.string(),image:z110.string().nullable(),createdAt:z110.string(),organizationCount:z110.number(),projectCount:z110.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z110.object({id:z110.string(),name:z110.string(),displayName:z110.string().nullable(),createdAt:z110.string(),organizationId:z110.string(),organizationName:z110.string(),ownerId:z110.string(),ownerName:z110.string().nullable(),ownerEmail:z110.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z110.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z111}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z111.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z111.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z111.object({command:z111.string().min(1).max(1e4),cwd:z111.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z111.record(z111.string(),z111.string()).optional(),name:z111.string().optional(),waitForCompletion:z111.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z111.object({identifier:z111.string(),status:SandboxProcessStatusSchema,command:z111.string().optional(),startedAt:z111.string().optional(),exitCode:z111.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema2(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z111.object({processes:z111.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema2(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z111.object({processId:z111.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z111.object({success:z111.boolean(),message:z111.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema2(PresetCommandResponseDTOSchema)}});import{z as z112}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common2();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_control_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_hosted_preview_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_branch_discard_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["symbolic-ref","--short","-q","HEAD"],cwd)}async function commitSubjectOrNull(cwd,sha){try{return await runGit(["log","-1","--format=%s",sha,"--"],cwd)}catch{return null}}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function gitErrorSummary(error){let lines=extractStderr(error).split(`
|
|
200
|
+
`).map(line=>line.trim()).filter(line=>line.length>0);return(lines.find(line=>line.startsWith("fatal:")||line.startsWith("error:"))??lines[0]??"git failed").replace(/\/\/[^/\s@]*@/g,"//")}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(commitSubjectOrNull,"commitSubjectOrNull");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(gitErrorSummary,"gitErrorSummary");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveBranchFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{branch:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||!isValidBranch(branch)?null:{branch,source:"branch"}}catch{return null}}function resolveBranchFromEnvironment(){let branch=process.env.FIMO_ENV?.trim();return branch&&isValidBranch(branch)?branch:null}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let branch,source,readOnly=!1;if(opts.branchOverride!==void 0){if(!isValidBranch(opts.branchOverride))throw new InvalidBranchOverrideError(opts.branchOverride);branch=opts.branchOverride,source="flag"}else 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)}
|
|
201
201
|
`)}if(bootstrapOpts.refuseReadOnly&&ctx.readOnly)throw new Error(`Refusing to run a mutating command against read-only Branch '${ctx.branch}'. Switch off the release/* tag or pass --branch <writable-branch>.`);return{ctx,fimo:createCliFimoClient(cfg,ctx.branch)}}var NotInProjectError,InvalidBranchOverrideError,BranchNotFoundError,GitBranchUndetectedError,init_project_context=__esm({"src/cli/utils/project-context.ts"(){init_esm();init_config();init_sdk_transport();init_git();init_project();NotInProjectError=class extends Error{static{__name(this,"NotInProjectError")}constructor(){super("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project."),this.name="NotInProjectError"}};__name(projectSettingsFromEnv,"projectSettingsFromEnv");InvalidBranchOverrideError=class extends Error{static{__name(this,"InvalidBranchOverrideError")}value;constructor(value){super(`--branch value '${value}' is invalid. Branch names must match /^[a-zA-Z0-9._/-]+$/, not start with '-', and be \u2264255 chars.`),this.name="InvalidBranchOverrideError",this.value=value}},BranchNotFoundError=class extends Error{static{__name(this,"BranchNotFoundError")}branch;knownBranches;constructor(branch,knownBranches){super(`Branch '${branch}' not found on the server. Known Branches: ${knownBranches.length>0?knownBranches.join(", "):"(none yet)"}.`),this.name="BranchNotFoundError",this.branch=branch,this.knownBranches=knownBranches}},GitBranchUndetectedError=class extends Error{static{__name(this,"GitBranchUndetectedError")}constructor(){super("Fimo could not detect a current Git Branch. Check out a Branch or pass --branch <name>."),this.name="GitBranchUndetectedError"}};__name(resolveBranchFromGit,"resolveBranchFromGit");__name(resolveBranchFromEnvironment,"resolveBranchFromEnvironment");__name(getProjectContext,"getProjectContext");__name(branchSourceBanner,"branchSourceBanner");__name(branchOverrideFromCommand,"branchOverrideFromCommand");__name(bootstrapProjectCommand,"bootstrapProjectCommand")}});var require_src=__commonJS({"../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2,module2){"use strict";var cursor={to(x,y2){return y2?`\x1B[${y2+1};${x+1}H`:`\x1B[${x+1}G`},move(x,y2){let ret="";return x<0?ret+=`\x1B[${-x}D`:x>0&&(ret+=`\x1B[${x}C`),y2<0?ret+=`\x1B[${-y2}A`:y2>0&&(ret+=`\x1B[${y2}B`),ret},up:__name((count=1)=>`\x1B[${count}A`,"up"),down:__name((count=1)=>`\x1B[${count}B`,"down"),forward:__name((count=1)=>`\x1B[${count}C`,"forward"),backward:__name((count=1)=>`\x1B[${count}D`,"backward"),nextLine:__name((count=1)=>"\x1B[E".repeat(count),"nextLine"),prevLine:__name((count=1)=>"\x1B[F".repeat(count),"prevLine"),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},scroll={up:__name((count=1)=>"\x1B[S".repeat(count),"up"),down:__name((count=1)=>"\x1B[T".repeat(count),"down")},erase={screen:"\x1B[2J",up:__name((count=1)=>"\x1B[1J".repeat(count),"up"),down:__name((count=1)=>"\x1B[J".repeat(count),"down"),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");return count&&(clear+=cursor.left),clear}};module2.exports={cursor,scroll,erase,beep:"\x07"}}});function recoverTenantApiBaseUrl(tenantApiUrl,projectId,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,branch,base)===normalized?base:void 0}catch{return}}function createIdentityService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{getCurrentSession(){return transport.request("/api/auth/get-session")}}}function createGitService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getRemote(projectId,branch){let body=await transport.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-remote`,{},{preserveForbidden:!0});if(!body.data.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(body.data.tenantApiUrl,projectId,branch);if(recovered)return{...body.data,tenantApiBaseUrl:recovered}}return body.data},async getCredential(projectId,branch){return(await transport.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-credential`,{},{preserveForbidden:!0})).data}}}function createPublicationControlService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return{async publish(projectId,request={}){return(await transport.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null},async unpublish(projectId){await transport.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}}}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function transferBlockersFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return[];let blockers=body.blockers;return Array.isArray(blockers)?blockers:[]}function createSandboxService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getHostedPreview(projectId,branch){return(await transport.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment2(branch)}/hosted-preview`)).data},async pull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&¶ms.set("noRestart","true"),options.wait!==void 0&¶ms.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(`
|
|
202
202
|
|
|
203
203
|
`);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
|
|
@@ -463,7 +463,7 @@ Full report: fimo agents report ${target.agentName} --session ${target.sessionId
|
|
|
463
463
|
${result.driftLines.map(l=>` ${l}`).join(`
|
|
464
464
|
`)}`,hint:"Run `fimo deploy` to push them first, or `fimo agents run --skip-drift-check` to dispatch the deployed version anyway."});return}if(result.skipped){let guidance=skipGuidance(result.skipped,name);if(guidance.code){ui.error({command:"agents run",code:guidance.code,message:guidance.message,details:{agent:name,skipped:result.skipped},hint:guidance.hint});return}ui.info({command:"agents run",message:`Dispatch was skipped: ${result.skipped}. ${guidance.message}`,jsonData:{agent:name,skipped:result.skipped},hint:guidance.hint});return}if(result.sessionId){ui.ok({command:"agents run",headline:`Triggered ${name} (session ${result.sessionId})`,details:{agent:name,session_id:result.sessionId},hint:`Watch progress: fimo agents runs ${name}`});return}ui.error({command:"agents run",code:"UNEXPECTED_RUN_RESPONSE",message:"Unexpected response from server (no sessionId, no skipped)."})}catch(err){printBundleError("agents run",err)}}__name(runAgentCommand,"runAgentCommand");init_dist();init_config();init_sdk_transport();init_project();async function agentRunsCommand(name,options){try{let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:200}),projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId2(projectRoot);if(!projectId){ui.error({command:"agents runs",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),fimo=createCliFimoClient(cfg),branch=options.branch,page;try{page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let pageNumber=parseCursorNumber(cursor,{defaultValue:1,minimum:1}),response=await fimo.execute("agents.runs",{projectId,agentName:name,branch,page:pageNumber,limit:pagination.limit});return{items:response.data,nextCursor:response.hasMore?String(response.page+1):null,total:response.total,page:response.page,totalPages:response.totalPages,hasMore:response.hasMore}},"fetchPage")})}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents runs",code:"AGENT_SESSIONS_FETCH_FAILED",message:`Failed to fetch sessions (HTTP ${err.status}): ${err.detail}`});return}throw err}let rows=page.items.map(session=>({id:session.id.slice(0,8),started:formatStartedAt(session.startedAt),duration:formatDuration(session.startedAt,session.finishedAt??session.cancelledAt),status:session.status,trigger:session.triggerKind,branch:session.branch,credits:session.creditsUsed==null?"\u2014":session.creditsUsed.toLocaleString("en-US")})),trailingArgs=[];branch&&trailingArgs.push("--branch",branch),options.project&&trailingArgs.push("--project",options.project),options.cwd&&trailingArgs.push("--cwd",options.cwd);let hint=page.nextCursor?buildPaginationHint(["fimo","agents","runs",name],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs}):void 0,jsonData={items:page.items,nextCursor:page.nextCursor,total:page.total,page:page.page,totalPages:page.totalPages,hasMore:page.hasMore};if(rows.length===0){ui.info({command:"agents runs",message:`(no recent sessions for '${name}'${branch?` on Branch '${branch}'`:""})`,jsonData});return}ui.table({command:"agents runs",columns:[{key:"id",label:"ID"},{key:"started",label:"STARTED"},{key:"duration",label:"DURATION"},{key:"status",label:"STATUS"},{key:"trigger",label:"TRIGGER"},{key:"branch",label:"BRANCH"},{key:"credits",label:"CREDITS"}],rows,jsonData,cellStyle:__name((row2,column)=>{if(column==="status")return statusRole(row2.status);if(column==="credits")return"dim"},"cellStyle"),...hint?{hint}:{}})}catch(err){if(err instanceof PaginationValidationError){ui.error({command:"agents runs",code:"AGENT_RUNS_INVALID_PAGINATION",message:err.message});return}printBundleError("agents runs",err)}}__name(agentRunsCommand,"agentRunsCommand");function readProjectId2(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId2,"readProjectId");function statusRole(status){switch(status){case"finished":return"success";case"errored":return"error";case"cancelled":return"warn";case"running":return"accent";default:return}}__name(statusRole,"statusRole");function formatStartedAt(startedAt){if(!startedAt)return"\u2014";let date=new Date(startedAt);return Number.isNaN(date.getTime())?"\u2014":date.toISOString().slice(0,16).replace("T"," ")}__name(formatStartedAt,"formatStartedAt");function formatDuration(startedAt,endedAt){if(!startedAt||!endedAt)return"\u2014";let start=new Date(startedAt),ms=new Date(endedAt).getTime()-start.getTime();if(Number.isNaN(ms)||ms<0)return"\u2014";if(ms<1e3)return`${ms}ms`;let secs=Math.floor(ms/1e3);if(secs<60)return`${secs}s`;let mins=Math.floor(secs/60),remainingSecs=secs%60;return`${mins}m${remainingSecs.toString().padStart(2,"0")}s`}__name(formatDuration,"formatDuration");init_dist();var import_yaml3=__toESM(require_dist(),1);import fs10 from"node:fs";import path12 from"node:path";var SECRET_KEY_RE=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_CONFIG_PREFIX2=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/;async function agentSecretsListCommand(name,opts){try{let config=readAgentConfig(name,opts.cwd),secrets=normalizeSecrets(config.secrets);if(secrets.length===0){ui.info({command:"agents secrets list",message:`No secrets requested by agent '${name}'.`});return}ui.table({command:"agents secrets list",columns:[{key:"key",label:"KEY"},{key:"requirement",label:"REQUIREMENT"},{key:"delivery",label:"DELIVERY"}],rows:secrets.map(secret=>({key:secret.key,requirement:secret.required===!1?"optional":"required",delivery:secret.delivery??"process_env"}))})}catch(err){printBundleError("agents secrets list",err)}}__name(agentSecretsListCommand,"agentSecretsListCommand");async function agentSecretsAddCommand(name,key,opts){try{validateSecretKey(key);let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),secrets=normalizeSecrets(config.secrets);secrets.some(secret=>secret.key===key)||(secrets.push({key,required:!opts.optional,delivery:"process_env"}),config.secrets=secrets,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config))),ui.ok({command:"agents secrets add",headline:`Agent '${name}' now requests secret ${key}`,details:{agent:name,key,optional:opts.optional===!0}})}catch(err){printBundleError("agents secrets add",err)}}__name(agentSecretsAddCommand,"agentSecretsAddCommand");async function agentSecretsRemoveCommand(name,key,opts){try{let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),after=normalizeSecrets(config.secrets).filter(secret=>secret.key!==key);config.secrets=after,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config)),ui.ok({command:"agents secrets remove",headline:`Agent '${name}' no longer requests secret ${key}`,details:{agent:name,key}})}catch(err){printBundleError("agents secrets remove",err)}}__name(agentSecretsRemoveCommand,"agentSecretsRemoveCommand");function normalizeSecrets(raw){if(!Array.isArray(raw))return[];let out=[];for(let item of raw){if(typeof item=="string"){out.push({key:item,required:!0,delivery:"process_env"});continue}if(item&&typeof item=="object"&&typeof item.key=="string"){let entry=item;out.push({key:entry.key,required:typeof entry.required=="boolean"?entry.required:!0,delivery:(entry.delivery==="process_env","process_env")})}}return out}__name(normalizeSecrets,"normalizeSecrets");function validateSecretKey(key){if(!SECRET_KEY_RE.test(key))throw new Error(`Secret key '${key}' must be UPPER_SNAKE_CASE.`);if(PUBLIC_CONFIG_PREFIX2.test(key))throw new Error(`Secret key '${key}' uses a public variable prefix. Use project variables for public values.`)}__name(validateSecretKey,"validateSecretKey");function readAgentConfig(name,cwd){return readAgentConfigWithPath(name,cwd).config}__name(readAgentConfig,"readAgentConfig");function readAgentConfigWithPath(name,cwd){let projectRoot=resolveProjectRoot(cwd??process.cwd()),filePath=path12.join(resolveAgentBundlesDir(projectRoot),name,"config.yaml");if(!fs10.existsSync(filePath))throw new Error(`Agent '${name}' does not have a config.yaml at ${filePath}.`);let parsed=(0,import_yaml3.parse)(fs10.readFileSync(filePath,"utf8")),config=parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:{};return{filePath,config}}__name(readAgentConfigWithPath,"readAgentConfigWithPath");init_dist();async function listTemplatesCommand(){let templates=listAgentTemplates();if(templates.length===0){ui.info({command:"agents list-templates",message:"No agent templates bundled with this CLI."});return}ui.result({command:"agents list-templates",data:{templates},render:__name(()=>{let lines=["Available templates:"],longest=templates.reduce((acc,t2)=>Math.max(acc,t2.name.length),0);for(let t2 of templates){let padded=t2.name.padEnd(longest);lines.push(` ${padded} ${t2.goalFirstLine??"(no GOAL.md)"}`)}return lines.push(""),lines.push(" Use `fimo agents create <name> --template <template>` to scaffold."),lines.join(`
|
|
465
465
|
`)},"render")})}__name(listTemplatesCommand,"listTemplatesCommand");import fs11 from"node:fs";import path13 from"node:path";init_dist();init_auth();init_config();init_sdk_transport();init_project_context();init_project();async function runValidateAgents(opts){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),agentsDir=resolveAgentBundlesDir(projectRoot),configPath=resolveProjectPolicyPath(projectRoot),policy=validatePolicy(configPath,projectRoot),bundleList=[];if(opts.name){if(!isValidAgentName(opts.name))return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[{pointer:"name",message:`Invalid agent name '${opts.name}'.`}]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};let bundle=await safeParse(path13.join(agentsDir,opts.name));if(!bundle.ok)return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[bundle.issue]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};bundleList=[bundle.bundle]}else bundleList=await listBundles(agentsDir);let reports=[],cloudNotifications=hasCloudNotificationRecipients(configPath);for(let bundle of bundleList){let report=validateOneBundle(bundle,bundleList);!cloudNotifications&&(bundle.config.triggers??[]).some(t2=>t2.type!=="manual")&&report.warnings.push({pointer:`${path13.basename(configPath)}:agents.notifications.email_recipients`,message:"Cloud triggers stay unwired until `agents.notifications.email_recipients` is non-empty (ADR-0009)."}),reports.push(report)}return{ok:(policy?.ok??!0)&&reports.every(r=>r.ok),policy,bundles:reports}}__name(runValidateAgents,"runValidateAgents");function hasCloudNotificationRecipients(policyPath){if(!fs11.existsSync(policyPath))return!1;try{return(parseFimoConfig(fs11.readFileSync(policyPath,"utf8"),{path:path13.basename(policyPath)}).agents?.notifications?.email_recipients??[]).length>0}catch{return!1}}__name(hasCloudNotificationRecipients,"hasCloudNotificationRecipients");function validatePolicy(policyPath,projectRoot){if(!fs11.existsSync(policyPath))return null;try{let text=fs11.readFileSync(policyPath,"utf8");return parseFimoConfig(text,{path:path13.relative(projectRoot,policyPath)}),{ok:!0,issues:[]}}catch(err){return{ok:!1,issues:[{pointer:path13.relative(projectRoot,policyPath),message:err.message,remediation:err.remediation}]}}}__name(validatePolicy,"validatePolicy");async function safeParse(bundlePath){try{return{ok:!0,bundle:await parseBundle(bundlePath)}}catch(err){return{ok:!1,issue:{pointer:path13.basename(bundlePath),message:err.message,remediation:err.remediation}}}}__name(safeParse,"safeParse");function validateOneBundle(bundle,allBundles){let phases={parse:{ok:!0,issues:[]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},vocab=validateAgainstVocabulary(bundle.capabilities,CAPABILITY_VOCABULARY);for(let token of vocab.unknown){let suggestion=suggestCapability(token),err=new BundleInvalidCapabilityError(token,"unknown",{suggestion:suggestion??void 0});phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}for(let token of vocab.nonDeclarable){let err=new BundleInvalidCapabilityError(token,"runtime_only");phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}let agentMap=new Map(allBundles.map(b=>[b.name,b])),compositionResult=composition_exports.validateComposition(bundle,agentMap);if(compositionResult.cycle){let err=new BundleCompositionCycleError(compositionResult.cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}for(let missingName of compositionResult.missing)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${missingName}]`,message:`Sub-agent '${missingName}' is referenced but not present in the project's agent-bundle directory.`,remediation:`Run \`fimo agents create ${missingName}\` or remove the reference from composition.sub-agents.`});for(let invalid of compositionResult.invalidGrants)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${invalid.subAgentName}].explicit_grants`,message:`explicit_grants references capabilities the sub-agent never declared: [${invalid.invalid.join(", ")}]. Declared: [${invalid.declared.join(", ")}].`,remediation:"Remove the undeclared tokens from explicit_grants, or add them to the sub-agent's capabilities.yaml."});if(!compositionResult.cycle){let cycle=detectCompositionCycle({root:bundle,agentMap});if(cycle){let err=new BundleCompositionCycleError(cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}}let issues=validateBundle(bundle,{availableAgents:allBundles}),warnings=[...bundle.warnings];for(let issue of issues){if(issue.severity==="warning"){warnings.push({pointer:issue.pointer,message:issue.message});continue}issue.pointer.startsWith("capabilities.yaml")||issue.pointer.startsWith("config.yaml:composition")||(phases.semantics.ok=!1,phases.semantics.issues.push({pointer:issue.pointer,message:issue.message}))}let ok=phases.parse.ok&&phases.capabilities.ok&&phases.composition.ok&&phases.semantics.ok;return{name:bundle.name,ok,phases,warnings}}__name(validateOneBundle,"validateOneBundle");async function runAvailabilityChecks(cwd){let projectRoot=resolveProjectRoot(cwd),projectId;try{projectId=loadProjectSettings(projectRoot).projectId}catch{if(projectId=process.env.FIMO_PROJECT_ID?.trim()??"",!projectId)return{ok:!0,skippedReason:"not-linked",issues:[]}}if(!process.env.FIMO_API_TOKEN?.trim()&&!readCredentials())return{ok:!0,skippedReason:"not-signed-in",issues:[]};let integrations=createIntegrationService(loadConfig()),context=await getProjectContext({cwd:projectRoot}),fimo=createCliFimoClient(loadConfig(),context.branch),{environment}=await fimo.execute("environments.resolve",{projectId,branch:context.branch}),agentsDir=resolveAgentBundlesDir(projectRoot),bundles=await listBundles(agentsDir),issues=[],configPath=__name(agentName=>path13.relative(projectRoot,path13.join(agentsDir,agentName,"config.yaml")).replaceAll("\\","/"),"configPath"),integrationsByAgent=bundles.map(bundle=>({name:bundle.name,integrations:Object.entries(agentIntegrationPolicy(bundle.config)).map(([integrationKey,entry])=>({integrationKey,enabled:entry.enabled,tools:enabledAgentIntegrationTools(entry),allTools:entry.tools===void 0,toolsConfigured:entry.tools!==void 0})).filter(entry=>entry.enabled)})).filter(entry=>entry.integrations.length>0);if(integrationsByAgent.length>0){let statuses=await integrations.list(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),infoByKey=new Map;for(let agent of integrationsByAgent)for(let integration of agent.integrations){let file=configPath(agent.name),status=statusByKey.get(integration.integrationKey);if(!status){issues.push({pointer:file,message:`${agent.name} allows unsupported integration ${integration.integrationKey}.`});continue}integration.toolsConfigured&&integration.tools.length===0&&issues.push({pointer:file,message:`${agent.name} enables ${integration.integrationKey}, but its tools map allows none. Remove the tools map to allow all available tools, or set at least one integrations.${integration.integrationKey}.tools.<tool>: true entry.`}),status.enabled||issues.push({pointer:file,message:`${agent.name} allows ${integration.integrationKey}, but the project integration is not enabled. Run: fimo integrations enable ${integration.integrationKey}`});let info=infoByKey.get(integration.integrationKey)??await integrations.getInfo(projectId,integration.integrationKey);infoByKey.set(integration.integrationKey,info);let knownTools=new Set(info.tools.map(tool=>tool.key)),effectiveTools=integration.allTools?[...knownTools]:integration.tools;for(let tool of effectiveTools)knownTools.has(tool)||issues.push({pointer:file,message:`${agent.name} allows unknown ${integration.integrationKey}.${tool} tool. Supported tools: ${[...knownTools].sort().join(", ")}`})}}let secretsByAgent=bundles.map(bundle=>({name:bundle.name,keys:(bundle.config.secrets??[]).filter(secret=>secret.required!==!1).map(secret=>secret.key)})).filter(entry=>entry.keys.length>0);if(secretsByAgent.length>0){let defined=new Set((await fimo.execute("secrets.list",{projectId,kind:"secret",environment})).map(secret=>secret.key));for(let entry of secretsByAgent)for(let key of entry.keys)defined.has(key)||issues.push({pointer:configPath(entry.name),message:`${entry.name} requires project secret ${key}, but it is not set. Run: fimo secrets add ${key} --stdin`})}return{ok:issues.length===0,skippedReason:null,issues}}__name(runAvailabilityChecks,"runAvailabilityChecks");async function validateAgentsCommand(opts){let report;try{report=await runValidateAgents(opts)}catch(err){throw printBundleError("agents validate",err),opts.noExit||(process.exitCode=1),err}return report.bundles.length===0&&!report.policy?(ui.info({command:"agents validate",message:"No bundles or Fimo project config found."}),report):(report.availability=await runAvailabilityChecks(opts.cwd??process.cwd()),report.availability.ok||(report.ok=!1),ui.result({command:"agents validate",data:report,render:__name(()=>renderReportHuman(report),"render")}),!report.ok&&!opts.noExit&&(process.exitCode=1),report)}__name(validateAgentsCommand,"validateAgentsCommand");function renderReportHuman(report){let lines=[];if(report.policy)if(report.policy.ok)lines.push(" \u2713 Fimo config policy ok");else{lines.push(" \u2717 Fimo config");for(let issue of report.policy.issues)lines.push(` \u2717 ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}for(let bundle of report.bundles)if(bundle.ok){lines.push(` \u2713 ${bundle.name} all phases ok`);for(let w3 of bundle.warnings)lines.push(` ! ${w3.pointer}: ${w3.message}`)}else{lines.push(` \u2717 ${bundle.name}`);for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)lines.push(` \u2717 [${phase}] ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}if(report.availability)if(report.availability.skippedReason){let why=report.availability.skippedReason==="not-signed-in"?"not signed in \u2014 run `fimo login`":"no linked project";lines.push(` \u21B7 integrations & secrets \u2014 skipped (${why})`)}else if(report.availability.ok)lines.push(" \u2713 integrations & secrets available");else{lines.push(" \u2717 integrations & secrets");for(let issue of report.availability.issues)lines.push(` \u2717 ${issue.message}`)}return lines.join(`
|
|
466
|
-
`)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--branch <branch>","Target Branch (default: main)").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),addPaginationOptions(agents.command("runs <name>").description("Paginated session list"),{defaultLimit:20,maxLimit:200}).option("--branch <branch>","Filter sessions to a specific Branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report brief; latest run unless --session is given").option("--session <id>","Target a specific session id").option("--details","Print the report's full evidence section as well as its brief").option("--branch <branch>","Pick the latest run on a specific Branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.device&&(params.device=options.device),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),{data:result}=await fimo.execute("analytics.pageviews",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),{items}=await fimo.execute("analytics.top",{projectId:ctx.projectId,branch:ctx.branch,dimension,...parseRangeOptions(options)}),limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),{annotations:annotations2}=await fimo.execute("analytics.annotationsList",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),result=(await fimo.execute("analytics.annotationsSet",{projectId:ctx.projectId,branch:ctx.branch,date,content:content2}))?.data??null;ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await fimo.execute("analytics.annotationsDelete",{projectId:ctx.projectId,branch:ctx.branch,date}),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await fimo.execute("assets.get",{projectId:ctx.projectId,branch:ctx.branch,id});if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");import fs12 from"node:fs";import path14 from"node:path";import{styleText as y}from"node:util";import{stdout as S,stdin as $}from"node:process";import P from"node:readline";var isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide");var ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index>=length&&index>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index>=length)break;if(LATIN_RE.lastIndex=index,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=EMOJI_RE.lastIndex;continue}index+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth;var NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth;var ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last=words.length;for(;last&&!dist_default2(words[last-1]);)last--;return last===words.length?string:words.slice(0,last).join(" ")+words.slice(last).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index=0;index<words.length;index++){let word=words[index];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
466
|
+
`)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--branch <branch>","Target Branch (default: main)").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),addPaginationOptions(agents.command("runs <name>").description("Paginated session list"),{defaultLimit:20,maxLimit:200}).option("--branch <branch>","Filter sessions to a specific Branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report brief; latest run unless --session is given").option("--session <id>","Target a specific session id").option("--details","Print the report's full evidence section as well as its brief").option("--branch <branch>","Pick the latest run on a specific Branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_esm();init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.device&&(params.device=options.device),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{data:result}=await fimo.execute("analytics.pageviews",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{items,branch}=await fimo.execute("analytics.top",{projectId:ctx.projectId,branch:ctx.branch,dimension,...parseRangeOptions(options)}),limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{branch,dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{annotations:annotations2,branch}=await fimo.execute("analytics.annotationsList",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics annotations list",data:{branch,annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),result=(await fimo.execute("analytics.annotationsSet",{projectId:ctx.projectId,branch:ctx.branch,date,content:content2}))?.data??null;ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await fimo.execute("analytics.annotationsDelete",{projectId:ctx.projectId,branch:ctx.branch,date}),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await fimo.execute("assets.get",{projectId:ctx.projectId,branch:ctx.branch,id});if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");import fs12 from"node:fs";import path14 from"node:path";import{styleText as y}from"node:util";import{stdout as S,stdin as $}from"node:process";import P from"node:readline";var isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide");var ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index>=length&&index>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index>=length)break;if(LATIN_RE.lastIndex=index,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=EMOJI_RE.lastIndex;continue}index+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth;var NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth;var ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last=words.length;for(;last&&!dist_default2(words[last-1]);)last--;return last===words.length?string:words.slice(0,last).join(" ")+words.slice(last).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index=0;index<words.length;index++){let word=words[index];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
467
467
|
`),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate)inSurrogate=character>="\uD800"&&character<="\uDBFF";else continue;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code2=Number.parseFloat(groups.code);escapeCode=code2===END_CODE?void 0:code2}else groups?.uri!==void 0&&(escapeUrl=groups.uri.length===0?void 0:groups.uri)}if(preString[i+1]===`
|
|
468
468
|
`){escapeUrl&&(returnValue+=wrapAnsiHyperlink(""));let closingCode=escapeCode?getClosingCode(escapeCode):void 0;escapeCode&&closingCode&&(returnValue+=wrapAnsiCode(closingCode))}else character===`
|
|
469
469
|
`&&(escapeCode&&getClosingCode(escapeCode)&&(returnValue+=wrapAnsiCode(escapeCode)),escapeUrl&&(returnValue+=wrapAnsiHyperlink(escapeUrl)))}return returnValue},"exec"),CRLF_OR_LF=/\r?\n/;function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map(line=>exec(line,columns,options)).join(`
|
|
@@ -523,10 +523,10 @@ ${a}${o}
|
|
|
523
523
|
`}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()?`
|
|
524
524
|
${c2}`:""}`}default:{let o=i?`${t("cyan",d2)} `:"",c2=i?t("cyan",E2):"";return`${s}${o}${u2}
|
|
525
525
|
${c2}
|
|
526
|
-
`}}}}).prompt(),"Ot");init_dist();init_config();import{z as z115}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
|
|
526
|
+
`}}}}).prompt(),"Ot");init_dist();init_config();import{z as z115}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(`
|
|
527
527
|
`).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=z115.object({sourceId:z115.string().min(1),path:z115.string().min(1),name:z115.string().min(1).optional(),parentId:z115.string().min(1).optional(),folderPath:z115.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z115.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:
|
|
528
528
|
${issues.join(`
|
|
529
|
-
`)}`)}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}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);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 params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),params.limit=String(pagination.limit);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 content2.listAssets(ctx.projectId,{...params,offset:String(offset)});return toOffsetPaginationPage(response)},"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(scope=>scope.referenceCount??scope.references.length,"scopeCount");function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope=>[scope.scope,scopeCount(scope)])),referenceCount=scopes.reduce((total,scope)=>total+scopeCount(scope),0),codeReferenceCount=scopes.reduce((total,scope)=>total+(scope.codeReferenceCount??0),0);return{status:scopes.some(scope=>scope.coverage!=="complete"||scope.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope=>[scope.scope,scope.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 project? This cannot be undone.`:`Permanently destroy asset ${id} across the project? 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
|
+
`)}`)}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(scope=>scope.referenceCount??scope.references.length,"scopeCount");function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope=>[scope.scope,scopeCount(scope)])),referenceCount=scopes.reduce((total,scope)=>total+scopeCount(scope),0),codeReferenceCount=scopes.reduce((total,scope)=>total+(scope.codeReferenceCount??0),0);return{status:scopes.some(scope=>scope.coverage!=="complete"||scope.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope=>[scope.scope,scope.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 project? This cannot be undone.`:`Permanently destroy asset ${id} across the project? 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(`
|
|
530
530
|
`)}__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 project 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 project. 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 project channel bindings").addHelpText("after",`
|
|
531
531
|
Examples:
|
|
532
532
|
fimo channels bind slack:#launch
|
|
@@ -541,7 +541,7 @@ Run \`fimo channels <command> --help\` for command-specific help.
|
|
|
541
541
|
`)}__name(formatReportHuman,"formatReportHuman");function formatPhaseHuman(phase){let out=[],header=phase.skipped?`\u21B7 ${phase.name} \u2014 skipped (${phase.skipped.reason})`:phase.ok?`\u2713 ${phase.name}`:`\u2717 ${phase.name}`;if(out.push(header),phase.stats){let parts=Object.entries(phase.stats).map(([k,v])=>`${k}: ${v}`);parts.length>0&&out.push(` ${parts.join(", ")}`)}for(let err of phase.errors){let loc=err.file?` (${err.file}${err.line?`:${err.line}`:""}${err.column?`:${err.column}`:""})`:"";out.push(` [${err.kind}] ${err.rule}: ${err.message}${loc}`)}return out.join(`
|
|
542
542
|
`)}__name(formatPhaseHuman,"formatPhaseHuman");init_config();init_sdk_transport();init_project_services();init_project_services();init_project_services();init_branch_checkout();import fs16 from"node:fs";import path19 from"node:path";var DEP_FIELDS=["dependencies","devDependencies"],DEPENDENCY_LOCKFILES=["pnpm-lock.yaml","package-lock.json","npm-shrinkwrap.json","yarn.lock","bun.lock","bun.lockb"];function resolveDevFimoDependencyForDeploy(cwd){let packagePath=path19.join(cwd,"package.json");if(!fs16.existsSync(packagePath))return null;let original=fs16.readFileSync(packagePath,"utf8"),pkg=JSON.parse(original),fileSpec=findLocalFimoSpec(pkg);if(!fileSpec)return null;let localPackageRoot=resolveFileSpec(fileSpec,cwd);if(isInsideProject(cwd,localPackageRoot))return null;let devRelease=readDevReleaseVersion(localPackageRoot);if(!devRelease.version||!devRelease.devJsonPath)throw new Error(`Found local fimo dependency "${fileSpec}", but no .fimo/dev.json with an exact development package exists above ${localPackageRoot}. Run \`pnpm -F fimo publish-cli -- --id <task-name>\` from that Fimo checkout, then retry.`);return{devJsonPath:devRelease.devJsonPath,packagePath,version:devRelease.version}}__name(resolveDevFimoDependencyForDeploy,"resolveDevFimoDependencyForDeploy");function prepareDevFimoDependencyForDeploy(cwd,selection=resolveDevFimoDependencyForDeploy(cwd)){if(!selection)return null;let original=fs16.readFileSync(selection.packagePath,"utf8"),pkg=JSON.parse(original),lockfiles=snapshotDependencyLockfiles(cwd);if(!rewriteFimoDep(pkg,selection.version))return null;try{fs16.writeFileSync(selection.packagePath,JSON.stringify(pkg,null,2)+`
|
|
543
543
|
`);for(let lockfile of lockfiles)fs16.rmSync(lockfile.path)}catch(error){restoreFile(selection.packagePath,Buffer.from(original));for(let lockfile of lockfiles)restoreFile(lockfile.path,lockfile.content,lockfile.mode);throw error}return{...selection,restore:__name(()=>{restoreFile(selection.packagePath,Buffer.from(original));for(let lockfile of lockfiles)restoreFile(lockfile.path,lockfile.content,lockfile.mode)},"restore")}}__name(prepareDevFimoDependencyForDeploy,"prepareDevFimoDependencyForDeploy");function snapshotDependencyLockfiles(cwd){return DEPENDENCY_LOCKFILES.flatMap(name=>{let lockfilePath=path19.join(cwd,name);return fs16.existsSync(lockfilePath)?[{content:fs16.readFileSync(lockfilePath),mode:fs16.statSync(lockfilePath).mode,path:lockfilePath}]:[]})}__name(snapshotDependencyLockfiles,"snapshotDependencyLockfiles");function restoreFile(filePath,content2,mode2){fs16.writeFileSync(filePath,content2,mode2===void 0?void 0:{mode:mode2})}__name(restoreFile,"restoreFile");function findLocalFimoSpec(pkg){for(let field of DEP_FIELDS){let spec=pkg[field]?.fimo;if(typeof spec=="string"&&spec.startsWith("file:"))return spec}return null}__name(findLocalFimoSpec,"findLocalFimoSpec");function resolveFileSpec(spec,cwd){let rawPath=spec.slice(5),packagePath=path19.isAbsolute(rawPath)?rawPath:path19.resolve(cwd,rawPath);return path19.resolve(packagePath)}__name(resolveFileSpec,"resolveFileSpec");function isInsideProject(cwd,targetPath){let relative3=path19.relative(path19.resolve(cwd),path19.resolve(targetPath));return relative3===""||!relative3.startsWith("..")&&!path19.isAbsolute(relative3)}__name(isInsideProject,"isInsideProject");init_git_credential_setup();init_git();init_git();import fs17 from"node:fs";import path20 from"node:path";var LOCKFILE_MANAGERS=[["pnpm-lock.yaml","pnpm"],["bun.lockb","bun"],["bun.lock","bun"],["yarn.lock","yarn"],["package-lock.json","npm"]],LOCKFILES=LOCKFILE_MANAGERS.map(([lockfile])=>lockfile),REMEDIATION='Commit one supported lockfile (pnpm-lock.yaml, yarn.lock, package-lock.json, bun.lock, or bun.lockb) or set an exact "packageManager" in package.json (for example "yarn@1.22.22").',FIRST_UNSUPPORTED_PNPM_MAJOR=12,EXACT_PACKAGE_MANAGER=/^(npm|pnpm|yarn|bun)@(\d+)\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function getPackageManagerPinWarning(cwd){let projectPackage=readPackageJson(path20.join(cwd,"package.json"));if(!projectPackage)return null;let packageManager=projectPackage.packageManager;if(typeof packageManager=="string"&&isExactPackageManager(packageManager))return null;let lockfiles=LOCKFILES.filter(lockfile=>fs17.existsSync(path20.join(cwd,lockfile)));return["package.json does not pin an exact package-manager version.",lockfiles.length===0?"Fimo will default to npm.":lockfiles.length===1?`Fimo will infer the package manager from ${lockfiles[0]}.`:`Fimo found multiple lockfiles (${lockfiles.join(", ")}), so package-manager selection is ambiguous.`,'Add a value such as "packageManager": "yarn@4.5.0" for reproducible local and Fimo installs.'].join(" ")}__name(getPackageManagerPinWarning,"getPackageManagerPinWarning");async function resolvePackageManagerContract(cwd){let projectPackage=readPackageJson(path20.join(cwd,"package.json"));if(!projectPackage)return{status:"not-applicable"};let declared=typeof projectPackage.packageManager=="string"?projectPackage.packageManager.trim():"";if(declared){let selection=parseExactPackageManager(declared);return selection?selection.manager==="pnpm"&&selection.major>=FIRST_UNSUPPORTED_PNPM_MAJOR?{status:"unresolved",violation:"unsupported",message:`package.json declares "packageManager": ${JSON.stringify(declared)}, but Fimo currently supports pnpm 11.x and earlier. Pin an exact supported version (for example "pnpm@11.5.2"), reinstall dependencies, and commit the updated pnpm-lock.yaml.`}:{status:"declared",packageManager:declared}:{status:"unresolved",violation:"not-exact",message:`package.json declares "packageManager": ${JSON.stringify(declared)}, which does not name one reproducible version of a supported package manager (npm, pnpm, yarn, bun). ${REMEDIATION}`}}if(!await isGitRepo(cwd))return{status:"not-applicable"};let tracked=await listTrackedLockfiles(cwd);if(tracked.length===1){let[lockfile,manager]=tracked[0];return{status:"inferred",manager,lockfile,warning:`package.json does not pin an exact package-manager version. Fimo will infer ${manager} from the committed ${lockfile}. Set "packageManager" in package.json for a reproducible version.`}}if(tracked.length>1)return{status:"unresolved",violation:"ambiguous-lockfiles",message:`The deployed tree commits several lockfiles (${tracked.map(([lockfile])=>lockfile).join(", ")}) and package.json does not declare which package manager wins. ${REMEDIATION}`};let untracked=LOCKFILES.filter(lockfile=>fs17.existsSync(path20.join(cwd,lockfile)));return untracked.length>0?{status:"unresolved",violation:"lockfile-not-tracked",message:`Git does not track ${untracked.join(", ")}, so the deployed tree carries no package-manager signal and the install may pick the wrong tool or version. ${REMEDIATION}`}:{status:"unresolved",violation:"no-signal",message:`The deployed tree has no package-manager signal: package.json declares no "packageManager" and no supported lockfile is committed. ${REMEDIATION}`}}__name(resolvePackageManagerContract,"resolvePackageManagerContract");async function listTrackedLockfiles(cwd){let stdout=await runGit(["ls-files","--",...LOCKFILES],cwd),tracked=new Set(stdout.split(`
|
|
544
|
-
`).map(line=>line.trim()).filter(Boolean));return LOCKFILE_MANAGERS.filter(([lockfile])=>tracked.has(lockfile))}__name(listTrackedLockfiles,"listTrackedLockfiles");function readPackageJson(filePath){try{return JSON.parse(fs17.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson,"readPackageJson");function isExactPackageManager(value){return parseExactPackageManager(value)!==null}__name(isExactPackageManager,"isExactPackageManager");function parseExactPackageManager(value){let match=EXACT_PACKAGE_MANAGER.exec(value.trim());return match?{manager:match[1],major:Number(match[2])}:null}__name(parseExactPackageManager,"parseExactPackageManager");init_project_context();init_project();init_dist();import{readFile as readFile3}from"node:fs/promises";import path29 from"node:path";var import_frameworks=__toESM(require_frameworks(),1),import_detect_framework=__toESM(require_detect_framework(),1),import_local_file_system_detector=__toESM(require_local_file_system_detector(),1);import{readFile}from"node:fs/promises";import{resolve}from"node:path";var FRAMEWORK_LIST=import_frameworks.frameworks;function detectorFor(projectRoot){return new import_local_file_system_detector.LocalFileSystemDetector(resolve(projectRoot))}__name(detectorFor,"detectorFor");async function readPackageManifest(projectRoot){try{return JSON.parse(await readFile(resolve(projectRoot,"package.json"),"utf8"))}catch{return{}}}__name(readPackageManifest,"readPackageManifest");function packageNameFor(framework){return[...framework.detectors?.every??[],...framework.detectors?.some??[]].find(detector=>detector.matchPackage)?.matchPackage??framework.dependency}__name(packageNameFor,"packageNameFor");function declaredVersionFor(framework,manifest){if(framework.detectedVersion)return framework.detectedVersion;let packageName=packageNameFor(framework);if(packageName)for(let group of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let version=manifest[group]?.[packageName];if(version)return version}}__name(declaredVersionFor,"declaredVersionFor");function normalizeFramework(framework,manifest){if(!framework.slug)return null;let declaredVersion=declaredVersionFor(framework,manifest);return{slug:framework.slug==="sveltekit-1"?"sveltekit":framework.slug,name:framework.slug==="sveltekit-1"?"SvelteKit":framework.name,...declaredVersion?{declaredVersion}:{}}}__name(normalizeFramework,"normalizeFramework");async function detectProjectFramework(projectRoot){let[framework,manifest]=await Promise.all([(0,import_detect_framework.detectFrameworkRecord)({fs:detectorFor(projectRoot),frameworkList:FRAMEWORK_LIST}),readPackageManifest(projectRoot)]);return framework?normalizeFramework(framework,manifest):null}__name(detectProjectFramework,"detectProjectFramework");init_project_layout();import{existsSync,readFileSync}from"fs";import{resolve as resolve2}from"path";var defaultConfig={seo:void 0};function getConfigServer(rootDir){try{return readConfigServer(rootDir)}catch{return defaultConfig}}__name(getConfigServer,"getConfigServer");function readConfigServer(rootDir){let configPath=resolveFimoConfigPath(rootDir),content2=readFileSync(configPath,"utf-8"),raw=JSON.parse(content2);return{runtime:raw.runtime,hosting:raw.hosting,seo:raw.seo,i18n:raw.i18n,routes:raw.routes,version:raw.version}}__name(readConfigServer,"readConfigServer");function resolveFimoConfigPath(rootDir){let existing=[CURRENT_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(candidate=>existsSync(resolve2(rootDir,candidate)));return resolve2(rootDir,selectProjectConfigPath(existing))}__name(resolveFimoConfigPath,"resolveFimoConfigPath");import{existsSync as existsSync2,readFileSync as readFileSync2,readdirSync,statSync}from"node:fs";import{createRequire}from"node:module";import{join as join3}from"node:path";var require2=createRequire(import.meta.url),parseSync;function parse5(filePath,code2){return parseSync??=require2("oxc-parser").parseSync,parseSync(filePath,code2)}__name(parse5,"parse");function findSourceFiles(dir,files=[]){if(!existsSync2(dir))return files;let entries2=readdirSync(dir);for(let entry of entries2){let fullPath=join3(dir,entry);if(statSync(fullPath).isDirectory()){if(entry==="ui"||entry==="node_modules")continue;findSourceFiles(fullPath,files)}else/\.(ts|tsx|js|jsx|svelte)$/.test(entry)&&files.push(fullPath)}return files}__name(findSourceFiles,"findSourceFiles");function importedNames(body,source,importedName){let names=new Set;for(let statement of body)if(!(statement.type!=="ImportDeclaration"||statement.source.value!==source))for(let specifier of statement.specifiers)specifier.type==="ImportSpecifier"&&specifier.imported.type==="Identifier"&&specifier.imported.name===importedName&&names.add(specifier.local.name);return names}__name(importedNames,"importedNames");function extractFromModule(filePath,code2,parsePath=filePath){let declarations=[],ast=parse5(parsePath,code2).program,fimoLabelNames=new Set([...importedNames(ast.body,"fimo-react","Label"),...importedNames(ast.body,"fimo/ui","Label")]);function visit2(node){if(!(!node||typeof node!="object")){if(node.type==="CallExpression"){let callee=node.callee;if(callee?.type==="Identifier"&&callee.name==="t"||callee?.type==="MemberExpression"&&callee.computed===!1&&callee.object?.type==="Identifier"&&callee.object.name==="labels"&&callee.property?.type==="Identifier"&&callee.property.name==="t"){let firstArg=(node.arguments||[])[0];firstArg?.type==="Literal"&&typeof firstArg.value=="string"&&declarations.push({key:firstArg.value,file:filePath})}}if(node.type==="JSXOpeningElement"&&node.name?.type==="JSXIdentifier"&&fimoLabelNames.has(node.name.name))for(let attribute of node.attributes??[])attribute?.type==="JSXAttribute"&&attribute.name?.type==="JSXIdentifier"&&attribute.name.name==="value"&&attribute.value?.type==="Literal"&&typeof attribute.value.value=="string"&&declarations.push({key:attribute.value.value,file:filePath});for(let key of Object.keys(node)){let child=node[key];if(Array.isArray(child))for(let item of child)visit2(item);else typeof child=="object"&&child!==null&&visit2(child)}}}return __name(visit2,"visit"),visit2(ast),declarations}__name(extractFromModule,"extractFromModule");var SVELTE_SCRIPT=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,SVELTE_COMMENT=/<!--[\s\S]*?-->/g,SVELTE_T_CALL_KEY=/(?:\blabels\.t|(?<![\w$.])t)\(\s*(['"])([^'"]*)\1/g;function extractFromSvelte(filePath,code2){let declarations=[],labelNames=new Set,markup=code2.replace(SVELTE_SCRIPT,(_script,contents)=>{let ast=parse5(`${filePath}.ts`,contents).program;for(let moduleName of["fimo-sveltekit/components","fimo/sveltekit/components"])for(let name of importedNames(ast.body,moduleName,"Label"))labelNames.add(name);return declarations.push(...extractFromModule(filePath,contents,`${filePath}.ts`)),""}).replace(SVELTE_COMMENT,"");for(let name of labelNames){let labelKey=new RegExp(`<${name}\\b[^>]*?\\svalue=(?:"([^"]*)"|'([^']*)')`,"g");for(let match of markup.matchAll(labelKey))declarations.push({key:match[1]??match[2],file:filePath})}for(let match of markup.matchAll(SVELTE_T_CALL_KEY))declarations.push({key:match[2],file:filePath});return declarations}__name(extractFromSvelte,"extractFromSvelte");function extractFromFile(filePath){try{let code2=readFileSync2(filePath,"utf-8");return filePath.endsWith(".svelte")?extractFromSvelte(filePath,code2):extractFromModule(filePath,code2)}catch(error){return console.error(`Failed to parse ${filePath}:`,error),[]}}__name(extractFromFile,"extractFromFile");function extractLabelKeys(options={}){let cwd=options.cwd??process.cwd(),srcDir=join3(cwd,"src"),declarations=[],seen=new Set;for(let file of findSourceFiles(srcDir))for(let declaration of extractFromFile(file))seen.has(declaration.key)||(seen.add(declaration.key),declarations.push(declaration));return declarations.sort((a,b)=>a.key.localeCompare(b.key))}__name(extractLabelKeys,"extractLabelKeys");function extractTranslations(options={}){return{keys:extractLabelKeys(options)}}__name(extractTranslations,"extractTranslations");import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";var SPLIT_LOWER_UPPER_RE=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),SPLIT_UPPER_UPPER_RE=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),SPLIT_SEPARATE_NUMBER_RE=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),DEFAULT_STRIP_REGEXP=/[^\p{L}\d]+/giu,SPLIT_REPLACE_VALUE="$1\0$2",DEFAULT_PREFIX_SUFFIX_CHARACTERS="";function split(value){let result=value.trim();result=result.replace(SPLIT_LOWER_UPPER_RE,SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE,SPLIT_REPLACE_VALUE),result=result.replace(DEFAULT_STRIP_REGEXP,"\0");let start=0,end=result.length;for(;result.charAt(start)==="\0";)start++;if(start===end)return[];for(;result.charAt(end-1)==="\0";)end--;return result.slice(start,end).split(/\0/g)}__name(split,"split");function splitSeparateNumbers(value){let words=split(value);for(let i=0;i<words.length;i++){let word=words[i],match=SPLIT_SEPARATE_NUMBER_RE.exec(word);if(match){let offset=match.index+(match[1]??match[2]).length;words.splice(i,1,word.slice(0,offset),word.slice(offset))}}return words}__name(splitSeparateNumbers,"splitSeparateNumbers");function camelCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map((word,index)=>index===0?lower(word):transform(word,index)).join(options?.delimiter??"")+suffix}__name(camelCase,"camelCase");function pascalCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map(transform).join(options?.delimiter??"")+suffix}__name(pascalCase,"pascalCase");function lowerFactory(locale){return locale===!1?input=>input.toLowerCase():input=>input.toLocaleLowerCase(locale)}__name(lowerFactory,"lowerFactory");function upperFactory(locale){return locale===!1?input=>input.toUpperCase():input=>input.toLocaleUpperCase(locale)}__name(upperFactory,"upperFactory");function capitalCaseTransformFactory(lower,upper){return word=>`${upper(word[0])}${lower(word.slice(1))}`}__name(capitalCaseTransformFactory,"capitalCaseTransformFactory");function pascalCaseTransformFactory(lower,upper){return(word,index)=>{let char0=word[0];return(index>0&&char0>="0"&&char0<="9"?"_"+char0:upper(char0))+lower(word.slice(1))}}__name(pascalCaseTransformFactory,"pascalCaseTransformFactory");function splitPrefixSuffix(input,options={}){let splitFn=options.split??(options.separateNumbers?splitSeparateNumbers:split),prefixCharacters=options.prefixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,suffixCharacters=options.suffixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,prefixIndex=0,suffixIndex=input.length;for(;prefixIndex<input.length;){let char=input.charAt(prefixIndex);if(!prefixCharacters.includes(char))break;prefixIndex++}for(;suffixIndex>prefixIndex;){let index=suffixIndex-1,char=input.charAt(index);if(!suffixCharacters.includes(char))break;suffixIndex=index}return[input.slice(0,prefixIndex),splitFn(input.slice(prefixIndex,suffixIndex)),input.slice(suffixIndex)]}__name(splitPrefixSuffix,"splitPrefixSuffix");import*as path21 from"node:path";import*as fs18 from"node:fs";var Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val){this.cache[key]=val}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};function ParseErr(message,str,indx){let whitespace=str.slice(0,indx).split(/\n/),lineNo=whitespace.length,colNo=whitespace[lineNo-1].length+1;throw message+=" at line "+lineNo+" col "+colNo+`:
|
|
544
|
+
`).map(line=>line.trim()).filter(Boolean));return LOCKFILE_MANAGERS.filter(([lockfile])=>tracked.has(lockfile))}__name(listTrackedLockfiles,"listTrackedLockfiles");function readPackageJson(filePath){try{return JSON.parse(fs17.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson,"readPackageJson");function isExactPackageManager(value){return parseExactPackageManager(value)!==null}__name(isExactPackageManager,"isExactPackageManager");function parseExactPackageManager(value){let match=EXACT_PACKAGE_MANAGER.exec(value.trim());return match?{manager:match[1],major:Number(match[2])}:null}__name(parseExactPackageManager,"parseExactPackageManager");init_project_context();init_project();init_dist();import{readFileSync as readFileSync9,readdirSync as readdirSync7}from"node:fs";import{readFile as readFile3}from"node:fs/promises";import{createRequire as createRequire3}from"node:module";import path29 from"node:path";var import_frameworks=__toESM(require_frameworks(),1),import_detect_framework=__toESM(require_detect_framework(),1),import_local_file_system_detector=__toESM(require_local_file_system_detector(),1);import{readFile}from"node:fs/promises";import{resolve}from"node:path";var FRAMEWORK_LIST=import_frameworks.frameworks;function detectorFor(projectRoot){return new import_local_file_system_detector.LocalFileSystemDetector(resolve(projectRoot))}__name(detectorFor,"detectorFor");async function readPackageManifest(projectRoot){try{return JSON.parse(await readFile(resolve(projectRoot,"package.json"),"utf8"))}catch{return{}}}__name(readPackageManifest,"readPackageManifest");function packageNameFor(framework){return[...framework.detectors?.every??[],...framework.detectors?.some??[]].find(detector=>detector.matchPackage)?.matchPackage??framework.dependency}__name(packageNameFor,"packageNameFor");function declaredVersionFor(framework,manifest){if(framework.detectedVersion)return framework.detectedVersion;let packageName=packageNameFor(framework);if(packageName)for(let group of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let version=manifest[group]?.[packageName];if(version)return version}}__name(declaredVersionFor,"declaredVersionFor");function normalizeFramework(framework,manifest){if(!framework.slug)return null;let declaredVersion=declaredVersionFor(framework,manifest);return{slug:framework.slug==="sveltekit-1"?"sveltekit":framework.slug,name:framework.slug==="sveltekit-1"?"SvelteKit":framework.name,...declaredVersion?{declaredVersion}:{}}}__name(normalizeFramework,"normalizeFramework");async function detectProjectFramework(projectRoot){let[framework,manifest]=await Promise.all([(0,import_detect_framework.detectFrameworkRecord)({fs:detectorFor(projectRoot),frameworkList:FRAMEWORK_LIST}),readPackageManifest(projectRoot)]);return framework?normalizeFramework(framework,manifest):null}__name(detectProjectFramework,"detectProjectFramework");var SPLIT_LOWER_UPPER_RE=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),SPLIT_UPPER_UPPER_RE=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),SPLIT_SEPARATE_NUMBER_RE=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),DEFAULT_STRIP_REGEXP=/[^\p{L}\d]+/giu,SPLIT_REPLACE_VALUE="$1\0$2",DEFAULT_PREFIX_SUFFIX_CHARACTERS="";function split(value){let result=value.trim();result=result.replace(SPLIT_LOWER_UPPER_RE,SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE,SPLIT_REPLACE_VALUE),result=result.replace(DEFAULT_STRIP_REGEXP,"\0");let start=0,end=result.length;for(;result.charAt(start)==="\0";)start++;if(start===end)return[];for(;result.charAt(end-1)==="\0";)end--;return result.slice(start,end).split(/\0/g)}__name(split,"split");function splitSeparateNumbers(value){let words=split(value);for(let i=0;i<words.length;i++){let word=words[i],match=SPLIT_SEPARATE_NUMBER_RE.exec(word);if(match){let offset=match.index+(match[1]??match[2]).length;words.splice(i,1,word.slice(0,offset),word.slice(offset))}}return words}__name(splitSeparateNumbers,"splitSeparateNumbers");function camelCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map((word,index)=>index===0?lower(word):transform(word,index)).join(options?.delimiter??"")+suffix}__name(camelCase,"camelCase");function pascalCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map(transform).join(options?.delimiter??"")+suffix}__name(pascalCase,"pascalCase");function lowerFactory(locale){return locale===!1?input=>input.toLowerCase():input=>input.toLocaleLowerCase(locale)}__name(lowerFactory,"lowerFactory");function upperFactory(locale){return locale===!1?input=>input.toUpperCase():input=>input.toLocaleUpperCase(locale)}__name(upperFactory,"upperFactory");function capitalCaseTransformFactory(lower,upper){return word=>`${upper(word[0])}${lower(word.slice(1))}`}__name(capitalCaseTransformFactory,"capitalCaseTransformFactory");function pascalCaseTransformFactory(lower,upper){return(word,index)=>{let char0=word[0];return(index>0&&char0>="0"&&char0<="9"?"_"+char0:upper(char0))+lower(word.slice(1))}}__name(pascalCaseTransformFactory,"pascalCaseTransformFactory");function splitPrefixSuffix(input,options={}){let splitFn=options.split??(options.separateNumbers?splitSeparateNumbers:split),prefixCharacters=options.prefixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,suffixCharacters=options.suffixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,prefixIndex=0,suffixIndex=input.length;for(;prefixIndex<input.length;){let char=input.charAt(prefixIndex);if(!prefixCharacters.includes(char))break;prefixIndex++}for(;suffixIndex>prefixIndex;){let index=suffixIndex-1,char=input.charAt(index);if(!suffixCharacters.includes(char))break;suffixIndex=index}return[input.slice(0,prefixIndex),splitFn(input.slice(prefixIndex,suffixIndex)),input.slice(suffixIndex)]}__name(splitPrefixSuffix,"splitPrefixSuffix");init_project_layout();import{existsSync,readFileSync}from"fs";import{resolve as resolve2}from"path";var defaultConfig={seo:void 0};function getConfigServer(rootDir){try{return readConfigServer(rootDir)}catch{return defaultConfig}}__name(getConfigServer,"getConfigServer");function readConfigServer(rootDir){let configPath=resolveFimoConfigPath(rootDir),content2=readFileSync(configPath,"utf-8"),raw=JSON.parse(content2);return{runtime:raw.runtime,hosting:raw.hosting,seo:raw.seo,i18n:raw.i18n,routes:raw.routes,version:raw.version}}__name(readConfigServer,"readConfigServer");function resolveFimoConfigPath(rootDir){let existing=[CURRENT_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(candidate=>existsSync(resolve2(rootDir,candidate)));return resolve2(rootDir,selectProjectConfigPath(existing))}__name(resolveFimoConfigPath,"resolveFimoConfigPath");import{existsSync as existsSync2,readFileSync as readFileSync2,readdirSync,statSync}from"node:fs";import{createRequire}from"node:module";import{join as join3}from"node:path";var require2=createRequire(import.meta.url),parseSync;function parse5(filePath,code2){return parseSync??=require2("oxc-parser").parseSync,parseSync(filePath,code2)}__name(parse5,"parse");function findSourceFiles(dir,files=[]){if(!existsSync2(dir))return files;let entries2=readdirSync(dir);for(let entry of entries2){let fullPath=join3(dir,entry);if(statSync(fullPath).isDirectory()){if(entry==="ui"||entry==="node_modules")continue;findSourceFiles(fullPath,files)}else/\.(ts|tsx|js|jsx|svelte)$/.test(entry)&&files.push(fullPath)}return files}__name(findSourceFiles,"findSourceFiles");function importedNames(body,source,importedName){let names=new Set;for(let statement of body)if(!(statement.type!=="ImportDeclaration"||statement.source.value!==source))for(let specifier of statement.specifiers)specifier.type==="ImportSpecifier"&&specifier.imported.type==="Identifier"&&specifier.imported.name===importedName&&names.add(specifier.local.name);return names}__name(importedNames,"importedNames");function extractFromModule(filePath,code2,parsePath=filePath){let declarations=[],ast=parse5(parsePath,code2).program,fimoLabelNames=new Set([...importedNames(ast.body,"fimo-react","Label"),...importedNames(ast.body,"fimo/ui","Label")]);function visit2(node){if(!(!node||typeof node!="object")){if(node.type==="CallExpression"){let callee=node.callee;if(callee?.type==="Identifier"&&callee.name==="t"||callee?.type==="MemberExpression"&&callee.computed===!1&&callee.object?.type==="Identifier"&&callee.object.name==="labels"&&callee.property?.type==="Identifier"&&callee.property.name==="t"){let firstArg=(node.arguments||[])[0];firstArg?.type==="Literal"&&typeof firstArg.value=="string"&&declarations.push({key:firstArg.value,file:filePath})}}if(node.type==="JSXOpeningElement"&&node.name?.type==="JSXIdentifier"&&fimoLabelNames.has(node.name.name))for(let attribute of node.attributes??[])attribute?.type==="JSXAttribute"&&attribute.name?.type==="JSXIdentifier"&&attribute.name.name==="value"&&attribute.value?.type==="Literal"&&typeof attribute.value.value=="string"&&declarations.push({key:attribute.value.value,file:filePath});for(let key of Object.keys(node)){let child=node[key];if(Array.isArray(child))for(let item of child)visit2(item);else typeof child=="object"&&child!==null&&visit2(child)}}}return __name(visit2,"visit"),visit2(ast),declarations}__name(extractFromModule,"extractFromModule");var SVELTE_SCRIPT=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,SVELTE_COMMENT=/<!--[\s\S]*?-->/g,SVELTE_T_CALL_KEY=/(?:\blabels\.t|(?<![\w$.])t)\(\s*(['"])([^'"]*)\1/g;function extractFromSvelte(filePath,code2){let declarations=[],labelNames=new Set,markup=code2.replace(SVELTE_SCRIPT,(_script,contents)=>{let ast=parse5(`${filePath}.ts`,contents).program;for(let moduleName of["fimo-sveltekit/components","fimo/sveltekit/components"])for(let name of importedNames(ast.body,moduleName,"Label"))labelNames.add(name);return declarations.push(...extractFromModule(filePath,contents,`${filePath}.ts`)),""}).replace(SVELTE_COMMENT,"");for(let name of labelNames){let labelKey=new RegExp(`<${name}\\b[^>]*?\\svalue=(?:"([^"]*)"|'([^']*)')`,"g");for(let match of markup.matchAll(labelKey))declarations.push({key:match[1]??match[2],file:filePath})}for(let match of markup.matchAll(SVELTE_T_CALL_KEY))declarations.push({key:match[2],file:filePath});return declarations}__name(extractFromSvelte,"extractFromSvelte");function extractFromFile(filePath){try{let code2=readFileSync2(filePath,"utf-8");return filePath.endsWith(".svelte")?extractFromSvelte(filePath,code2):extractFromModule(filePath,code2)}catch(error){return console.error(`Failed to parse ${filePath}:`,error),[]}}__name(extractFromFile,"extractFromFile");function extractLabelKeys(options={}){let cwd=options.cwd??process.cwd(),srcDir=join3(cwd,"src"),declarations=[],seen=new Set;for(let file of findSourceFiles(srcDir))for(let declaration of extractFromFile(file))seen.has(declaration.key)||(seen.add(declaration.key),declarations.push(declaration));return declarations.sort((a,b)=>a.key.localeCompare(b.key))}__name(extractLabelKeys,"extractLabelKeys");function extractTranslations(options={}){return{keys:extractLabelKeys(options)}}__name(extractTranslations,"extractTranslations");import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";import*as path21 from"node:path";import*as fs18 from"node:fs";var Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val){this.cache[key]=val}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};function ParseErr(message,str,indx){let whitespace=str.slice(0,indx).split(/\n/),lineNo=whitespace.length,colNo=whitespace[lineNo-1].length+1;throw message+=" at line "+lineNo+" col "+colNo+`:
|
|
545
545
|
|
|
546
546
|
`+str.split(/\n/)[lineNo-1]+`
|
|
547
547
|
`+Array(colNo).join(" ")+"^",new EtaParseError(message)}__name(ParseErr,"ParseErr");function RuntimeErr(originalError,str,lineNo,path52){let lines=str.split(`
|
|
@@ -593,7 +593,7 @@ ${imports}
|
|
|
593
593
|
export const content = {
|
|
594
594
|
${entries2}
|
|
595
595
|
} as const;
|
|
596
|
-
`}__name(renderContentRegistry,"renderContentRegistry");function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}__name(normalizeFields,"normalizeFields");function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}__name(referenceImportsFor,"referenceImportsFor");function collectFieldRuntimeTypeImports(field,imports){if(!field||typeof field!="object"||Array.isArray(field))return;let definition=field;switch(definition.type){case"boolean":imports.add("FimoBoolean");return;case"media":imports.add("FimoMedia");return;case"reference":imports.add(Array.isArray(definition.targets)&&definition.targets.length>0?"FimoPolymorphicReference":"FimoReference");return;case"richtext":imports.add("FimoRichText"),imports.add("FimoRichTextContent");return;case"blocks":{let schema=definition.schema;if(!schema||typeof schema!="object"||Array.isArray(schema))return;let blockSchema=schema,fieldGroups=Array.isArray(blockSchema.oneOf)?blockSchema.oneOf.map(variant=>variant&&typeof variant=="object"&&!Array.isArray(variant)?variant.fields:void 0):[blockSchema.fields];for(let fields of fieldGroups)if(!(!fields||typeof fields!="object"||Array.isArray(fields)))for(let nestedField of Object.values(fields))collectFieldRuntimeTypeImports(nestedField,imports);return}default:return}}__name(collectFieldRuntimeTypeImports,"collectFieldRuntimeTypeImports");function runtimeTypeImportsFor(fields){let imports=new Set(["Fields","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"]);for(let field of Object.values(fields))collectFieldRuntimeTypeImports(field,imports);return RUNTIME_TYPE_IMPORT_ORDER.filter(typeImport=>imports.has(typeImport))}__name(runtimeTypeImportsFor,"runtimeTypeImportsFor");function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields),runtimeTypeImports:runtimeTypeImportsFor(fields)}}__name(schemaToModel,"schemaToModel");function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=runtime?contentRuntimeImportFor(options.framework,runtime):"fimo-react",generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__name(syncSchemas,"syncSchemas");init_esm();import fs20 from"node:fs";import path23 from"node:path";init_esm();import fs19 from"node:fs";import path22 from"node:path";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function fieldList(value){return typeof value=="string"?[value]:Array.isArray(value)?value.filter(item=>typeof item=="string"):[]}__name(fieldList,"fieldList");function queryFields(query){if(!isRecord(query))return[];let fields=new Set;if(isRecord(query.where))for(let field of Object.keys(query.where))field.startsWith("$")||fields.add(field.split(".")[0]);for(let sort of fieldList(query.sort))fields.add(sort.replace(/^-/,"").split(".")[0]);for(let field of[...fieldList(query.fields),...fieldList(query.populate)])fields.add(field.split(".")[0]);return[...fields]}__name(queryFields,"queryFields");function readSchemas(cwd){let directory=path22.join(cwd,"src/schemas");if(!fs19.existsSync(directory))return null;let schemas3=new Map;for(let file of fs19.readdirSync(directory).filter(name=>name.endsWith(".json"))){let fallbackUid=path22.basename(file,".json"),value;try{value=JSON.parse(fs19.readFileSync(path22.join(directory,file),"utf8"))}catch{schemas3.set(fallbackUid,{fields:{},isSingleton:!1,valid:!1});continue}if(!isRecord(value)){schemas3.set(fallbackUid,{fields:{},isSingleton:!1,valid:!1});continue}let uid=typeof value.uid=="string"&&value.uid?value.uid:fallbackUid;schemas3.set(uid,{fields:isRecord(value.fields)?value.fields:{},isSingleton:value.isSingleton===!0,valid:!0})}return schemas3}__name(readSchemas,"readSchemas");function schemaFields(schema){return new Set([...Object.keys(schema.fields),"id","slug"])}__name(schemaFields,"schemaFields");function queryableFields(schema){return new Set([...schemaFields(schema),"createdAt","updatedAt"])}__name(queryableFields,"queryableFields");function validateQuery(query,pointer,schema,params,schemas3){let errors=[],unknownField=queryFields(query).find(field=>!queryableFields(schema).has(field));unknownField&&errors.push(`${pointer}: Query field "${unknownField}" does not exist on the referenced schema.`);for(let expression of pageSourceParamExpressions(query)){let parsed=parsePageParamExpression(expression),binding=parsed?params[parsed.param]:void 0;if(!parsed||!binding||typeof binding.schema!="string")continue;let boundSchema=schemas3.get(binding.schema),field=parsed.field.split(".")[0];boundSchema?.valid&&!schemaFields(boundSchema).has(field)&&errors.push(`${pointer}: ${expression} reads missing field "${field}" from schema "${binding.schema}".`)}return errors}__name(validateQuery,"validateQuery");function validatePageRegistrySchemaReferences(cwd,config,displayPath){let schemas3=readSchemas(cwd);if(!schemas3||!isRecord(config.routes))return[];let errors=[];for(let[routeId,rawRoute]of Object.entries(config.routes)){if(!isRecord(rawRoute))continue;let params=isRecord(rawRoute.params)?rawRoute.params:{};for(let[param,binding]of Object.entries(params)){let pointer=`${displayPath}#routes.${routeId}.params.${param}`;if(typeof binding.schema!="string")continue;let schema=schemas3.get(binding.schema);if(!schema){errors.push(`${pointer}.schema: Unknown schema "${binding.schema}".`);continue}if(!schema.valid)continue;schema.isSingleton&&errors.push(`${pointer}.schema: Page params require a Collection, but "${binding.schema}" is a Single.`);let fields=schemaFields(schema);for(let key of["queryField","displayField"]){let field=binding[key];typeof field=="string"&&!fields.has(field)&&errors.push(`${pointer}.${key}: Field "${field}" does not exist on schema "${binding.schema}".`)}if(typeof binding.queryField=="string"&&!["id","slug"].includes(binding.queryField)){let definition=schema.fields[binding.queryField];isRecord(definition)&&(definition.required!==!0&&errors.push(`${pointer}.queryField: Custom URL field "${binding.queryField}" must set "required": true.`),definition.unique!==!0&&errors.push(`${pointer}.queryField: Custom URL field "${binding.queryField}" must set "unique": true.`))}errors.push(...validateQuery(binding.query,`${pointer}.query`,schema,params,schemas3))}if(isRecord(rawRoute.sources))for(let[sourceName,source]of Object.entries(rawRoute.sources)){if(!isRecord(source)||source.type!=="single"&&source.type!=="collection")continue;let pointer=`${displayPath}#routes.${routeId}.sources.${sourceName}`;if(typeof source.schema!="string")continue;let schema=schemas3.get(source.schema);if(!schema){errors.push(`${pointer}.schema: Unknown schema "${source.schema}".`);continue}schema.valid&&(source.type==="single"&&!schema.isSingleton&&errors.push(`${pointer}.schema: Source expects a Single, but "${source.schema}" is a Collection.`),source.type==="collection"&&schema.isSingleton&&errors.push(`${pointer}.schema: Source expects a Collection, but "${source.schema}" is a Single.`),source.type==="collection"&&errors.push(...validateQuery(source.query,`${pointer}.query`,schema,params,schemas3)))}}return errors}__name(validatePageRegistrySchemaReferences,"validatePageRegistrySchemaReferences");function validateFimoConfig(cwd){let configPath=resolveFimoConfigPath(cwd);if(!fs20.existsSync(configPath))return{errors:[],configChecked:!1};let displayPath=path23.relative(cwd,configPath).replaceAll(path23.sep,"/"),value;try{value=JSON.parse(fs20.readFileSync(configPath,"utf8"))}catch{return{errors:[`${displayPath} must contain valid JSON.`],configChecked:!0}}let parsed=FimoAppConfigSchema.safeParse(value);return parsed.success?{errors:validatePageRegistrySchemaReferences(cwd,value,displayPath),configChecked:!0}:{errors:parsed.error.issues.map(issue=>{let pointer=issue.path.length>0?`#${issue.path.join(".")}`:"";return`${displayPath}${pointer}: ${issue.message}`}),configChecked:!0}}__name(validateFimoConfig,"validateFimoConfig");init_esm();import fs21 from"node:fs";import path24 from"node:path";var FIMO_LOCALE_PARAM="locale";function normalizeRoutePath(path52){let collapsed=(path52.startsWith("/")?path52:`/${path52}`).replace(/\/{2,}/g,"/");return collapsed.length>1?collapsed.replace(/\/+$/,""):collapsed}__name(normalizeRoutePath,"normalizeRoutePath");function splitSegments(path52){return path52.split("/").filter(Boolean)}__name(splitSegments,"splitSegments");function isPlaceholder(segment){return segment.startsWith(":")&&segment.length>1}__name(isPlaceholder,"isPlaceholder");function readPlaceholder(segment){return isPlaceholder(segment)?{name:segment.slice(1).replace(/[?*]$/,""),catchAll:segment.endsWith("*")}:null}__name(readPlaceholder,"readPlaceholder");function resolveParamType(name,descriptor2){return descriptor2?.type?descriptor2.type:name===FIMO_LOCALE_PARAM?"locale":"entry"}__name(resolveParamType,"resolveParamType");function buildLocaleParam(name,descriptor2,index,issues){if(name!==FIMO_LOCALE_PARAM)return issues.push({param:name,message:`Param "${name}" declares \`"type": "locale"\` but "${FIMO_LOCALE_PARAM}" is the only locale parameter name.`,fix:`Rename the path segment and the descriptor to ":${FIMO_LOCALE_PARAM}", or use \`"type": "entry"\`.`}),null;if(index!==0)return issues.push({param:name,message:`The ":${FIMO_LOCALE_PARAM}" segment must be the first segment of the path.`,fix:`Move it to the front, for example "/:${FIMO_LOCALE_PARAM}/blog/:slug".`}),null;for(let field of["schema","queryField","displayField","query"])descriptor2?.[field]!==void 0&&issues.push({param:name,message:`Locale param "${name}" must not declare "${field}" \u2014 the locale is read from the URL, never from the CMS.`,fix:`Remove "${field}" from \`params.${name}\`.`});return{type:"locale",name,optional:descriptor2?.optional!==!1}}__name(buildLocaleParam,"buildLocaleParam");function buildEntryParam(name,descriptor2,issues){return name===FIMO_LOCALE_PARAM?(issues.push({param:name,message:`Param "${name}" is reserved for the locale segment and cannot use \`"type": "entry"\`.`,fix:`Drop \`"type": "entry"\` from \`params.${name}\`, or rename the segment.`}),null):descriptor2?(descriptor2.optional!==void 0&&issues.push({param:name,message:`Entry param "${name}" cannot be optional \u2014 only the locale segment can be omitted from a URL.`,fix:`Remove "optional" from \`params.${name}\`.`}),!descriptor2.schema||!descriptor2.queryField?(issues.push({param:name,message:`Entry param "${name}" is missing ${descriptor2.schema?'"queryField"':'"schema"'}.`,fix:`Set \`"${name}": { "schema": "SchemaName", "queryField": "${name}" }\`.`}),null):{type:"entry",name,schema:descriptor2.schema,queryField:descriptor2.queryField,...descriptor2.displayField?{displayField:descriptor2.displayField}:{}}):(issues.push({param:name,message:`":${name}" needs \`params\` metadata before its URLs can be generated.`,fix:`Add \`"params": { "${name}": { "schema": "SchemaName", "queryField": "${name}" } }\`.`}),null)}__name(buildEntryParam,"buildEntryParam");function resolveRouteContract(id,route){let path52=normalizeRoutePath(route.path??"/"),segments=splitSegments(path52),declared=route.params??{},issues=[],params=[],unresolvedParams=[],seen=new Set;segments.forEach((segment,index)=>{if(!isPlaceholder(segment))return;let placeholder=readPlaceholder(segment);if(!placeholder)return;let{name}=placeholder;if(seen.has(name)){issues.push({param:name,message:`Placeholder ":${name}" appears more than once.`,fix:"Give each placeholder a distinct name."}),unresolvedParams.push(name);return}seen.add(name);let descriptor2=declared[name],resolved=resolveParamType(name,descriptor2)==="locale"?buildLocaleParam(name,descriptor2,index,issues):buildEntryParam(name,descriptor2,issues);resolved?params.push(resolved):unresolvedParams.push(name)});for(let name of Object.keys(declared))seen.has(name)||issues.push({param:name,message:`Declared param "${name}" has no ":${name}" segment in the path.`,fix:`Add ":${name}" to the path, or remove it from "params".`});let localeParam=params.find(param=>param.type==="locale")??null,canonicalPath=localeParam?normalizeRoutePath(`/${segments.filter(segment=>segment!==`:${FIMO_LOCALE_PARAM}`).join("/")}`):path52;return{id,config:route,path:path52,canonicalPath,params,entryParams:params.filter(param=>param.type==="entry"),localeParam,unresolvedParams,issues}}__name(resolveRouteContract,"resolveRouteContract");function parseRoutesSource(source){let stripped=source.replace(/\/\/.*$/gm,""),seen=new Set,routes=[];function add(entry){let key=`${entry.path??"<layout>"}|${entry.file}|${entry.isIndex?"index":"route"}|${entry.isLayout?"layout":""}`;seen.has(key)||(seen.add(key),routes.push(entry))}__name(add,"add");function normalizePath(p2){return p2?`/${p2}`.replace(/^\/\//,"/"):"/"}__name(normalizePath,"normalizePath");for(let match of stripped.matchAll(/\bindex\(\s*['"]([^'"]+)['"](?:\s*,[^)]*)?\)/g))add({path:"/",file:match[1],isIndex:!0});for(let match of stripped.matchAll(/\broute\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/g))add({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\blayout\(\s*['"]([^'"]+)['"]/g))add({path:null,file:match[1],isIndex:!1,isLayout:!0});for(let match of stripped.matchAll(/\{\s*path:\s*['"]([^'"]+)['"][^}]*?file:\s*['"]([^'"]+)['"][^}]*\}/g))add({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\{\s*file:\s*['"]([^'"]+)['"]([^}]*)\}/g)){let file=match[1],rest=match[2],pathMatch=rest.match(/path:\s*['"]([^'"]+)['"]/),isIndex=/index:\s*true/.test(rest);add({path:pathMatch?normalizePath(pathMatch[1]):"/",file,isIndex})}return routes}__name(parseRoutesSource,"parseRoutesSource");function readJson(filePath){try{return JSON.parse(fs21.readFileSync(filePath,"utf-8"))}catch{return{}}}__name(readJson,"readJson");function loadConfigRoutes(config){let configRoutes=config.routes??{};return Object.entries(configRoutes).map(([id,route])=>({id,path:route.path??"/",label:route.label??null,sources:route.sources??null,seo:route.seo??null,contract:resolveRouteContract(id,route)}))}__name(loadConfigRoutes,"loadConfigRoutes");function validateRouteMetadata(options={}){let cwd=options.cwd??process.cwd(),configFilePath=resolveFimoConfigPath(cwd),configDisplayPath=path24.relative(cwd,configFilePath).replaceAll(path24.sep,"/"),srcDir=path24.resolve(cwd,"src"),routesFilePath=path24.resolve(srcDir,"routes.ts"),errors=[],config=readJson(configFilePath),fileRoutes=[];if(!fs21.existsSync(routesFilePath))errors.push("Missing src/routes.ts.");else{let source=fs21.readFileSync(routesFilePath,"utf-8");fileRoutes=parseRoutesSource(source)}let pathToFile=new Map;for(let fr of fileRoutes)fr.path&&fr.file&&pathToFile.set(normalizeLocaleSpelling(fr.path),fr.file);let i18n=validateI18nConfig(config);errors.push(...i18n.errors);let configRoutes=loadConfigRoutes(config),configPaths=new Set(configRoutes.flatMap(registrablePaths));for(let fileRoute of fileRoutes)fileRoute.isLayout||fileRoute.path&&!configPaths.has(normalizeLocaleSpelling(fileRoute.path))&&errors.push(`Route with path "${fileRoute.path}" (file: "${fileRoute.file}") exists in src/routes.ts but has no matching entry in ${configDisplayPath}.
|
|
596
|
+
`}__name(renderContentRegistry,"renderContentRegistry");function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}__name(normalizeFields,"normalizeFields");function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}__name(referenceImportsFor,"referenceImportsFor");function collectFieldRuntimeTypeImports(field,imports){if(!field||typeof field!="object"||Array.isArray(field))return;let definition=field;switch(definition.type){case"boolean":imports.add("FimoBoolean");return;case"media":imports.add("FimoMedia");return;case"reference":imports.add(Array.isArray(definition.targets)&&definition.targets.length>0?"FimoPolymorphicReference":"FimoReference");return;case"richtext":imports.add("FimoRichText"),imports.add("FimoRichTextContent");return;case"blocks":{let schema=definition.schema;if(!schema||typeof schema!="object"||Array.isArray(schema))return;let blockSchema=schema,fieldGroups=Array.isArray(blockSchema.oneOf)?blockSchema.oneOf.map(variant=>variant&&typeof variant=="object"&&!Array.isArray(variant)?variant.fields:void 0):[blockSchema.fields];for(let fields of fieldGroups)if(!(!fields||typeof fields!="object"||Array.isArray(fields)))for(let nestedField of Object.values(fields))collectFieldRuntimeTypeImports(nestedField,imports);return}default:return}}__name(collectFieldRuntimeTypeImports,"collectFieldRuntimeTypeImports");function runtimeTypeImportsFor(fields){let imports=new Set(["Fields","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"]);for(let field of Object.values(fields))collectFieldRuntimeTypeImports(field,imports);return RUNTIME_TYPE_IMPORT_ORDER.filter(typeImport=>imports.has(typeImport))}__name(runtimeTypeImportsFor,"runtimeTypeImportsFor");function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields),runtimeTypeImports:runtimeTypeImportsFor(fields)}}__name(schemaToModel,"schemaToModel");function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=runtime?contentRuntimeImportFor(options.framework,runtime):"fimo-react",generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__name(syncSchemas,"syncSchemas");init_esm();import fs20 from"node:fs";import path23 from"node:path";init_esm();import fs19 from"node:fs";import path22 from"node:path";function isEntryBinding(binding){return isEntryParamBinding(binding)}__name(isEntryBinding,"isEntryBinding");function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function fieldList(value){return typeof value=="string"?[value]:Array.isArray(value)?value.filter(item=>typeof item=="string"):[]}__name(fieldList,"fieldList");function queryFields(query){if(!isRecord(query))return[];let fields=new Set;if(isRecord(query.where))for(let field of Object.keys(query.where))field.startsWith("$")||fields.add(field.split(".")[0]);for(let sort of fieldList(query.sort))fields.add(sort.replace(/^-/,"").split(".")[0]);for(let field of[...fieldList(query.fields),...fieldList(query.populate)])fields.add(field.split(".")[0]);return[...fields]}__name(queryFields,"queryFields");function readSchemas(cwd){let directory=path22.join(cwd,"src/schemas");if(!fs19.existsSync(directory))return null;let schemas3=new Map;for(let file of fs19.readdirSync(directory).filter(name=>name.endsWith(".json"))){let fallbackUid=path22.basename(file,".json"),value;try{value=JSON.parse(fs19.readFileSync(path22.join(directory,file),"utf8"))}catch{schemas3.set(fallbackUid,{fields:{},isSingleton:!1,valid:!1});continue}if(!isRecord(value)){schemas3.set(fallbackUid,{fields:{},isSingleton:!1,valid:!1});continue}let uid=typeof value.uid=="string"&&value.uid?value.uid:fallbackUid;schemas3.set(uid,{fields:isRecord(value.fields)?value.fields:{},isSingleton:value.isSingleton===!0,valid:!0})}return schemas3}__name(readSchemas,"readSchemas");function schemaFields(schema){return new Set([...Object.keys(schema.fields),"id","slug"])}__name(schemaFields,"schemaFields");function queryableFields(schema){return new Set([...schemaFields(schema),"createdAt","updatedAt"])}__name(queryableFields,"queryableFields");function validateQuery(query,pointer,schema,params,schemas3){let errors=[],unknownField=queryFields(query).find(field=>!queryableFields(schema).has(field));unknownField&&errors.push(`${pointer}: Query field "${unknownField}" does not exist on the referenced schema.`);for(let expression of pageSourceParamExpressions(query)){let parsed=parsePageParamExpression(expression),binding=parsed?params[parsed.param]:void 0;if(!parsed||!binding)continue;if(!isEntryBinding(binding)){errors.push(`${pointer}: ${expression} reads param "${parsed.param}", which is not a Collection entry param.`);continue}if(typeof binding.schema!="string")continue;let boundSchema=schemas3.get(binding.schema),field=parsed.field.split(".")[0];boundSchema?.valid&&!schemaFields(boundSchema).has(field)&&errors.push(`${pointer}: ${expression} reads missing field "${field}" from schema "${binding.schema}".`)}return errors}__name(validateQuery,"validateQuery");function validatePageRegistrySchemaReferences(cwd,config,displayPath){let schemas3=readSchemas(cwd);if(!schemas3||!isRecord(config.routes))return[];let errors=[];for(let[routeId,rawRoute]of Object.entries(config.routes)){if(!isRecord(rawRoute))continue;let params=isRecord(rawRoute.params)?rawRoute.params:{};for(let[param,binding]of Object.entries(params)){let pointer=`${displayPath}#routes.${routeId}.params.${param}`;if(!isEntryBinding(binding)||typeof binding.schema!="string")continue;let schema=schemas3.get(binding.schema);if(!schema){errors.push(`${pointer}.schema: Unknown schema "${binding.schema}".`);continue}if(!schema.valid)continue;schema.isSingleton&&errors.push(`${pointer}.schema: Page params require a Collection, but "${binding.schema}" is a Single.`);let fields=schemaFields(schema);for(let key of["queryField","displayField"]){let field=binding[key];typeof field=="string"&&!fields.has(field)&&errors.push(`${pointer}.${key}: Field "${field}" does not exist on schema "${binding.schema}".`)}if(typeof binding.queryField=="string"&&!["id","slug"].includes(binding.queryField)){let definition=schema.fields[binding.queryField];isRecord(definition)&&(definition.required!==!0&&errors.push(`${pointer}.queryField: Custom URL field "${binding.queryField}" must set "required": true.`),definition.unique!==!0&&errors.push(`${pointer}.queryField: Custom URL field "${binding.queryField}" must set "unique": true.`))}errors.push(...validateQuery(binding.query,`${pointer}.query`,schema,params,schemas3))}if(isRecord(rawRoute.sources))for(let[sourceName,source]of Object.entries(rawRoute.sources)){if(!isRecord(source)||source.type!=="single"&&source.type!=="collection")continue;let pointer=`${displayPath}#routes.${routeId}.sources.${sourceName}`;if(typeof source.schema!="string")continue;let schema=schemas3.get(source.schema);if(!schema){errors.push(`${pointer}.schema: Unknown schema "${source.schema}".`);continue}schema.valid&&(source.type==="single"&&!schema.isSingleton&&errors.push(`${pointer}.schema: Source expects a Single, but "${source.schema}" is a Collection.`),source.type==="collection"&&schema.isSingleton&&errors.push(`${pointer}.schema: Source expects a Collection, but "${source.schema}" is a Single.`),source.type==="collection"&&errors.push(...validateQuery(source.query,`${pointer}.query`,schema,params,schemas3)))}}return errors}__name(validatePageRegistrySchemaReferences,"validatePageRegistrySchemaReferences");function validateFimoConfig(cwd){let configPath=resolveFimoConfigPath(cwd);if(!fs20.existsSync(configPath))return{errors:[],configChecked:!1};let displayPath=path23.relative(cwd,configPath).replaceAll(path23.sep,"/"),value;try{value=JSON.parse(fs20.readFileSync(configPath,"utf8"))}catch{return{errors:[`${displayPath} must contain valid JSON.`],configChecked:!0}}let parsed=FimoAppConfigSchema.safeParse(value);return parsed.success?{errors:validatePageRegistrySchemaReferences(cwd,value,displayPath),configChecked:!0}:{errors:parsed.error.issues.map(issue=>{let pointer=issue.path.length>0?`#${issue.path.join(".")}`:"";return`${displayPath}${pointer}: ${issue.message}`}),configChecked:!0}}__name(validateFimoConfig,"validateFimoConfig");init_esm();import fs21 from"node:fs";import path24 from"node:path";var FIMO_LOCALE_PARAM="locale";function normalizeRoutePath(path52){let collapsed=(path52.startsWith("/")?path52:`/${path52}`).replace(/\/{2,}/g,"/");return collapsed.length>1?collapsed.replace(/\/+$/,""):collapsed}__name(normalizeRoutePath,"normalizeRoutePath");function splitSegments(path52){return path52.split("/").filter(Boolean)}__name(splitSegments,"splitSegments");function isPlaceholder(segment){return segment.startsWith(":")&&segment.length>1}__name(isPlaceholder,"isPlaceholder");function readPlaceholder(segment){return isPlaceholder(segment)?{name:segment.slice(1).replace(/[?*]$/,""),catchAll:segment.endsWith("*")}:null}__name(readPlaceholder,"readPlaceholder");function resolveParamType(name,descriptor2){return descriptor2?.type?descriptor2.type:name===FIMO_LOCALE_PARAM?"locale":"entry"}__name(resolveParamType,"resolveParamType");function buildLocaleParam(name,descriptor2,index,issues){if(name!==FIMO_LOCALE_PARAM)return issues.push({param:name,message:`Param "${name}" declares \`"type": "locale"\` but "${FIMO_LOCALE_PARAM}" is the only locale parameter name.`,fix:`Rename the path segment and the descriptor to ":${FIMO_LOCALE_PARAM}", or use \`"type": "entry"\`.`}),null;if(index!==0)return issues.push({param:name,message:`The ":${FIMO_LOCALE_PARAM}" segment must be the first segment of the path.`,fix:`Move it to the front, for example "/:${FIMO_LOCALE_PARAM}/blog/:slug".`}),null;for(let field of["schema","queryField","displayField","query"])descriptor2?.[field]!==void 0&&issues.push({param:name,message:`Locale param "${name}" must not declare "${field}" \u2014 the locale is read from the URL, never from the CMS.`,fix:`Remove "${field}" from \`params.${name}\`.`});return{type:"locale",name,optional:descriptor2?.optional!==!1}}__name(buildLocaleParam,"buildLocaleParam");function buildExternalParam(name,descriptor2,issues){if(name===FIMO_LOCALE_PARAM)return issues.push({param:name,message:`Param "${name}" is reserved for the locale segment and cannot use \`"type": "external"\`.`,fix:`Drop \`"type": "external"\` from \`params.${name}\`, or rename the segment.`}),null;for(let field of["schema","queryField","displayField","query","optional"])descriptor2[field]!==void 0&&issues.push({param:name,message:`External param "${name}" must not declare "${field}" \u2014 its values are owned by the application, never read from the CMS.`,fix:`Remove "${field}" from \`params.${name}\`.`});return{type:"external",name}}__name(buildExternalParam,"buildExternalParam");function buildEntryParam(name,descriptor2,issues){return name===FIMO_LOCALE_PARAM?(issues.push({param:name,message:`Param "${name}" is reserved for the locale segment and cannot use \`"type": "entry"\`.`,fix:`Drop \`"type": "entry"\` from \`params.${name}\`, or rename the segment.`}),null):descriptor2?(descriptor2.optional!==void 0&&issues.push({param:name,message:`Entry param "${name}" cannot be optional \u2014 only the locale segment can be omitted from a URL.`,fix:`Remove "optional" from \`params.${name}\`.`}),!descriptor2.schema||!descriptor2.queryField?(issues.push({param:name,message:`Entry param "${name}" is missing ${descriptor2.schema?'"queryField"':'"schema"'}.`,fix:`Set \`"${name}": { "schema": "SchemaName", "queryField": "${name}" }\`.`}),null):{type:"entry",name,schema:descriptor2.schema,queryField:descriptor2.queryField,...descriptor2.displayField?{displayField:descriptor2.displayField}:{}}):(issues.push({param:name,message:`":${name}" needs \`params\` metadata before its URLs can be generated.`,fix:`Add \`"params": { "${name}": { "schema": "SchemaName", "queryField": "${name}" } }\`.`}),null)}__name(buildEntryParam,"buildEntryParam");function resolveRouteContract(id,route){let path52=normalizeRoutePath(route.path??"/"),segments=splitSegments(path52),declared=route.params??{},issues=[],params=[],unresolvedParams=[],seen=new Set;segments.forEach((segment,index)=>{if(!isPlaceholder(segment))return;let placeholder=readPlaceholder(segment);if(!placeholder)return;let{name}=placeholder;if(seen.has(name)){issues.push({param:name,message:`Placeholder ":${name}" appears more than once.`,fix:"Give each placeholder a distinct name."}),unresolvedParams.push(name);return}seen.add(name);let descriptor2=declared[name],type=resolveParamType(name,descriptor2),resolved=type==="locale"?buildLocaleParam(name,descriptor2,index,issues):type==="external"&&descriptor2?buildExternalParam(name,descriptor2,issues):buildEntryParam(name,descriptor2,issues);resolved?params.push(resolved):unresolvedParams.push(name)});for(let name of Object.keys(declared))seen.has(name)||issues.push({param:name,message:`Declared param "${name}" has no ":${name}" segment in the path.`,fix:`Add ":${name}" to the path, or remove it from "params".`});let localeParam=params.find(param=>param.type==="locale")??null,canonicalPath=localeParam?normalizeRoutePath(`/${segments.filter(segment=>segment!==`:${FIMO_LOCALE_PARAM}`).join("/")}`):path52;return{id,config:route,path:path52,canonicalPath,params,entryParams:params.filter(param=>param.type==="entry"),externalParams:params.filter(param=>param.type==="external"),localeParam,unresolvedParams,issues}}__name(resolveRouteContract,"resolveRouteContract");function parseRoutesSource(source){let stripped=source.replace(/\/\/.*$/gm,""),seen=new Set,routes=[];function add(entry){let key=`${entry.path??"<layout>"}|${entry.file}|${entry.isIndex?"index":"route"}|${entry.isLayout?"layout":""}`;seen.has(key)||(seen.add(key),routes.push(entry))}__name(add,"add");function normalizePath(p2){return p2?`/${p2}`.replace(/^\/\//,"/"):"/"}__name(normalizePath,"normalizePath");for(let match of stripped.matchAll(/\bindex\(\s*['"]([^'"]+)['"](?:\s*,[^)]*)?\)/g))add({path:"/",file:match[1],isIndex:!0});for(let match of stripped.matchAll(/\broute\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/g))add({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\blayout\(\s*['"]([^'"]+)['"]/g))add({path:null,file:match[1],isIndex:!1,isLayout:!0});for(let match of stripped.matchAll(/\{\s*path:\s*['"]([^'"]+)['"][^}]*?file:\s*['"]([^'"]+)['"][^}]*\}/g))add({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\{\s*file:\s*['"]([^'"]+)['"]([^}]*)\}/g)){let file=match[1],rest=match[2],pathMatch=rest.match(/path:\s*['"]([^'"]+)['"]/),isIndex=/index:\s*true/.test(rest);add({path:pathMatch?normalizePath(pathMatch[1]):"/",file,isIndex})}return routes}__name(parseRoutesSource,"parseRoutesSource");function readJson(filePath){try{return JSON.parse(fs21.readFileSync(filePath,"utf-8"))}catch{return{}}}__name(readJson,"readJson");function loadConfigRoutes(config){let configRoutes=config.routes??{};return Object.entries(configRoutes).map(([id,route])=>({id,path:route.path??"/",label:route.label??null,sources:route.sources??null,seo:route.seo??null,contract:resolveRouteContract(id,route)}))}__name(loadConfigRoutes,"loadConfigRoutes");function validateRouteMetadata(options={}){let cwd=options.cwd??process.cwd(),configFilePath=resolveFimoConfigPath(cwd),configDisplayPath=path24.relative(cwd,configFilePath).replaceAll(path24.sep,"/"),srcDir=path24.resolve(cwd,"src"),routesFilePath=path24.resolve(srcDir,"routes.ts"),errors=[],config=readJson(configFilePath),fileRoutes=[];if(!fs21.existsSync(routesFilePath))errors.push("Missing src/routes.ts.");else{let source=fs21.readFileSync(routesFilePath,"utf-8");fileRoutes=parseRoutesSource(source)}let pathToFile=new Map;for(let fr of fileRoutes)fr.path&&fr.file&&pathToFile.set(normalizeLocaleSpelling(fr.path),fr.file);let i18n=validateI18nConfig(config);errors.push(...i18n.errors);let configRoutes=loadConfigRoutes(config),configPaths=new Set(configRoutes.flatMap(registrablePaths));for(let fileRoute of fileRoutes)fileRoute.isLayout||fileRoute.path&&!configPaths.has(normalizeLocaleSpelling(fileRoute.path))&&errors.push(`Route with path "${fileRoute.path}" (file: "${fileRoute.file}") exists in src/routes.ts but has no matching entry in ${configDisplayPath}.
|
|
597
597
|
Fix: add a route entry to ${configDisplayPath} "routes" with a matching "path".`);let filePaths=new Set(fileRoutes.filter(r=>!r.isLayout&&r.path).map(r=>normalizeLocaleSpelling(r.path)));for(let route of configRoutes)registrablePaths(route).some(candidate=>filePaths.has(candidate))||errors.push(`Route "${route.id}" (${route.path}) exists in ${configDisplayPath} but is not registered in src/routes.ts.
|
|
598
598
|
Fix: add the route to src/routes.ts. Example: route('${route.path.replace(/^\//,"")}', './pages/YourPage.tsx')`);i18n.routingStrategy==="path-prefix"&&i18n.locales.length>1&&errors.push(...validateLocaleRouteCollisions({configRoutes,fileRoutes,i18n,configDisplayPath,routesSourceUsesLegacyHelper:sourceUsesLegacyFimoRoutes(routesFilePath)}));let routeById=new Map;for(let route of configRoutes){if(routeById.has(route.id)){let previousPath=routeById.get(route.id).path;errors.push(`Duplicate route id "${route.id}" found for paths "${previousPath}" and "${route.path}".`);continue}routeById.set(route.id,route)}for(let route of configRoutes){for(let issue of route.contract.issues)errors.push(`Route "${route.id}" (${route.path}): ${issue.message}
|
|
599
599
|
Fix: ${issue.fix}`);errors.push(...validatePageSources(route))}errors.push(...validateRouteShapeCollisions(configRoutes));for(let route of configRoutes){let file=registrablePaths(route).map(candidate=>pathToFile.get(candidate)).find(Boolean);if(!file)continue;let routeModulePath=path24.resolve(srcDir,file);if(!fs21.existsSync(routeModulePath)){errors.push(`Route "${route.id}" (${route.path}) references missing module "${file}".
|
|
@@ -632,7 +632,7 @@ This breaks source tracking for inline editing. Translation keys must be statica
|
|
|
632
632
|
\u274C Found ${errors.length} error(s) in ${reactFiles.length} files.
|
|
633
633
|
`),process.exit(1)}}import fs25 from"node:fs";import path28 from"node:path";var SCAN_EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs"],SCAN_EXTENSIONS_SET=new Set(SCAN_EXTENSIONS),SKIP_DIRS=new Set(["node_modules","dist",".next",".fimo",".git","public"]),GLOBAL_PATTERNS=[/\.css$/,/\.scss$/,/tailwind\.config/,/postcss\.config/,/vite\.config/,/tsconfig/,/package\.json$/,/src\/main\.[tj]sx?$/,/src\/index\.[tj]sx?$/,/src\/root\.[tj]sx?$/,/react-router\.config/];function isGlobalFile(filePath){return GLOBAL_PATTERNS.some(p2=>p2.test(filePath))}__name(isGlobalFile,"isGlobalFile");function collectFiles(dir){let files=[];if(!fs25.existsSync(dir))return files;let entries2=fs25.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(SKIP_DIRS.has(entry.name))continue;let fullPath=path28.join(dir,entry.name);entry.isDirectory()?files.push(...collectFiles(fullPath)):SCAN_EXTENSIONS_SET.has(path28.extname(entry.name))&&files.push(fullPath)}return files}__name(collectFiles,"collectFiles");function extractImports(content2){let imports=[],staticRegex=/(?:import|export)\s+(?:[\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;for(let match of content2.matchAll(staticRegex))imports.push(match[1]);let dynamicRegex=/import\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(dynamicRegex))imports.push(match[1]);let requireRegex=/require\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(requireRegex))imports.push(match[1]);return imports.filter(s=>s.startsWith(".")||s.startsWith("@/"))}__name(extractImports,"extractImports");function resolveImport(specifier,fromDir,srcDir){let targetPath;if(specifier.startsWith("@/"))targetPath=path28.resolve(srcDir,specifier.slice(2));else if(specifier.startsWith("."))targetPath=path28.resolve(fromDir,specifier);else return null;if(fs25.existsSync(targetPath)&&fs25.statSync(targetPath).isFile())return targetPath;for(let ext of SCAN_EXTENSIONS){let withExt=targetPath+ext;if(fs25.existsSync(withExt))return withExt}for(let ext of SCAN_EXTENSIONS){let indexFile=path28.join(targetPath,"index"+ext);if(fs25.existsSync(indexFile))return indexFile}return null}__name(resolveImport,"resolveImport");function discoverRoutes(srcDir,root){let routesFilePath=path28.resolve(srcDir,"routes.ts");if(!fs25.existsSync(routesFilePath))return new Map;let source=fs25.readFileSync(routesFilePath,"utf-8"),parsed=parseRoutesSource(source),fileToRoutes=new Map;for(let r of parsed){if(r.isLayout||!r.path||!r.file)continue;let resolved=resolveImport(r.file,srcDir,srcDir);if(!resolved)continue;let rel=path28.relative(root,resolved);fileToRoutes.has(rel)||fileToRoutes.set(rel,new Set),fileToRoutes.get(rel).add(r.path)}return fileToRoutes}__name(discoverRoutes,"discoverRoutes");function buildReverseImportGraph(srcDir,root){let fileToImporters=new Map,allFiles=collectFiles(srcDir);for(let filePath of allFiles){let content2;try{content2=fs25.readFileSync(filePath,"utf-8")}catch{continue}let imports=extractImports(content2);for(let specifier of imports){let resolved=resolveImport(specifier,path28.dirname(filePath),srcDir);if(!resolved)continue;let resolvedRel=path28.relative(root,resolved),importerRel=path28.relative(root,filePath);fileToImporters.has(resolvedRel)||fileToImporters.set(resolvedRel,new Set),fileToImporters.get(resolvedRel).add(importerRel)}}return fileToImporters}__name(buildReverseImportGraph,"buildReverseImportGraph");function resolveAffectedRoutes(file,fileToImporters,fileToRoutes){let visited=new Set,queue=[file],affectedRoutes=new Set;for(;queue.length>0;){let current=queue.shift();if(visited.has(current))continue;visited.add(current);let routes=fileToRoutes.get(current);if(routes)for(let route of routes)affectedRoutes.add(route);let importers=fileToImporters.get(current);if(importers)for(let importer of importers)visited.has(importer)||queue.push(importer)}return Array.from(affectedRoutes)}__name(resolveAffectedRoutes,"resolveAffectedRoutes");function resolveRoutes(changedFiles,options={}){let root=options.cwd??process.cwd(),srcDir=path28.resolve(root,"src"),normalizedChangedFiles=changedFiles.map(f=>f.replace(/^\/+/,""));if(normalizedChangedFiles.length===0)return{routeMap:{},routes:[],unresolvedFiles:[]};let fileToRoutes=discoverRoutes(srcDir,root),fileToImporters=buildReverseImportGraph(srcDir,root),routeMap={},unresolvedFiles=[];for(let file of normalizedChangedFiles){if(isGlobalFile(file)){routeMap[file]=["*"];continue}let routes=resolveAffectedRoutes(file,fileToImporters,fileToRoutes);routes.length>0?routeMap[file]=routes:unresolvedFiles.push(file)}let allRoutes=[...new Set(Object.values(routeMap).flat().filter(r=>r!=="*"))];return{routeMap,routes:allRoutes,unresolvedFiles}}__name(resolveRoutes,"resolveRoutes");function resolveCwd(options){return options.cwd?resolve7(options.cwd):process.cwd()}__name(resolveCwd,"resolveCwd");function renderPrettyJson4(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson4,"renderPrettyJson");async function syncSchemasCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncSchemas({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-schemas",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncSchemasCommand,"syncSchemasCommand");async function syncFormsCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncForms({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-forms",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncFormsCommand,"syncFormsCommand");async function exportStaticCommand(options){let result=await exportStatic({cwd:resolveCwd(options)});ui.result({command:"export-static",data:result??{ok:!0},render:__name(()=>renderPrettyJson4(result??{ok:!0}),"render")})}__name(exportStaticCommand,"exportStaticCommand");function validateRouteMetadataCommand(options){let result=validateRouteMetadata({cwd:resolveCwd(options)});result.errors.length>0&&(ui.error({command:"scripts validate-route-metadata",code:"ROUTE_METADATA_INVALID",message:`Route metadata validation failed (${result.errors.length} issue(s)):
|
|
634
634
|
${result.errors.map(e=>` - ${e}`).join(`
|
|
635
|
-
`)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data,render:__name(()=>JSON.stringify(data),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root){if(!existsSync8(root))return[];let results=[];for(let name of readdirSync6(root)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),branchOverride2=branchOverrideFromCommand(cmd),dependencyWarnings=[],report=await runValidate({cwd,branchOverride:branchOverride2,onWarning:__name(warning=>dependencyWarnings.push(warning),"onWarning")}),packageManager=await resolvePackageManagerContract(cwd),warnings=[getDbLabelsRuntimeWarning(cwd),packageManager.status==="inferred"?packageManager.warning:null,...dependencyWarnings].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,branchOverride:branchOverride2,onWarning}=opts,checks=await runChecksPhase({cwd,onWarning}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,branchOverride:branchOverride2}),finalizeReport({phases:{checks,codegen,sync}})}__name(runValidate,"runValidate");async function runChecksPhase(opts){let{cwd,onWarning}=opts,[lintResult,routeResult,agentsResult,schemasResult,configResult,packageManagerResult,dependencyResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd})),Promise.resolve().then(()=>validateFimoConfig(cwd)),Promise.resolve().then(()=>resolvePackageManagerContract(cwd)),Promise.resolve().then(()=>inspectDependencyLifecycleScripts(cwd))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));if(configResult.status==="fulfilled"){stats.configsChecked=Number(configResult.value.configChecked);for(let message of configResult.value.errors)errors.push(authorError({rule:"fimo-config",message}))}else errors.push(infraErrorFromException("fimo-config",configResult.reason));if(packageManagerResult.status==="fulfilled"){let contract=packageManagerResult.value;contract.status==="unresolved"&&errors.push(authorError({rule:`package-manager/${contract.violation}`,message:contract.message,file:"package.json"}))}else errors.push(infraErrorFromException("package-manager",packageManagerResult.reason));return dependencyResult.status==="fulfilled"?dependencyResult.value.status==="warning"?onWarning?.(dependencyResult.value.message):dependencyResult.value.status==="blocked"&&errors.push(authorError({rule:"dependency-build-scripts",message:`${dependencyResult.value.packageManager} blocked lifecycle scripts for: ${dependencyResult.value.packages.join(", ")}. Add these packages to the project's explicit build-script approval policy, reinstall, and re-run validation.`})):onWarning?.(`Dependency lifecycle-script approval check skipped: inspection failed (${dependencyResult.reason instanceof Error?dependencyResult.reason.message:String(dependencyResult.reason)}).`),{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");async function runRouteMetadataCheck(opts){return(await detectProjectFramework(opts.cwd))?.slug!=="react-router"?null:validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,frameworkResult=detectProjectFramework(cwd),[schemasResult,formsResult,labelsResult]=await Promise.allSettled([frameworkResult.then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),frameworkResult.then(framework=>syncForms({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,branchOverride:branchOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,branchOverride:branchOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let fimo=createCliFimoClient(loadConfig(),ctx.branch),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(async()=>(await fimo.execute("labels.list",{projectId:ctx.projectId,branch:ctx.branch,locale})).data,"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Branch":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path29.join(cwd,".env")),...await readEnvFile(path29.join(cwd,".env.local"))};if(process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),!values.VITE_API_URL){let derived=resolveLocalRuntimeEnv({cwd});derived&&(values.VITE_API_URL=derived.tenantApiUrl,values.FIMO_ENV??=derived.env)}return values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index=trimmed.indexOf("=");if(index===-1)continue;let key=trimmed.slice(0,index).trim(),value=trimmed.slice(index+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){if(process.env.FIMO_MIGRATION_NO_DEPLOY==="1"){ui.error({command:"deploy",code:"MIGRATION_DEPLOY_BLOCKED",message:"Deployment is disabled while a migration is running.",hint:"Finish local migration and QA first, then request deployment separately."});return}let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let branchOverride2=branchOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,branchOverride:branchOverride2});if(isPretty2&&process.stderr.write(`${branchSourceBanner(ctx)}
|
|
635
|
+
`)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data,render:__name(()=>JSON.stringify(data),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root){if(!existsSync8(root))return[];let results=[];for(let name of readdirSync6(root)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),branchOverride2=branchOverrideFromCommand(cmd),dependencyWarnings=[],report=await runValidate({cwd,branchOverride:branchOverride2,onWarning:__name(warning=>dependencyWarnings.push(warning),"onWarning")}),packageManager=await resolvePackageManagerContract(cwd),warnings=[getDbLabelsRuntimeWarning(cwd),packageManager.status==="inferred"?packageManager.warning:null,...dependencyWarnings,...report.warnings.map(warning=>warning.message)].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,branchOverride:branchOverride2,onWarning}=opts,checks=await runChecksPhase({cwd,onWarning}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,branchOverride:branchOverride2}),{...finalizeReport({phases:{checks,codegen,sync}}),warnings:findContentTypesWithoutObservedConsumer(cwd)}}__name(runValidate,"runValidate");var SCHEMAS_DIR_REL="src/schemas",SOURCE_FILE_PATTERN=/\.(?:[cm]?[jt]sx?|astro|svelte|vue)$/,IGNORED_SCAN_DIRS=new Set(["node_modules","dist","build","out","coverage"]),require4=createRequire3(import.meta.url);function findContentTypesWithoutObservedConsumer(cwd){let definitions=readSchemaDefinitions(cwd);if(definitions.length===0)return[];let sources=readProjectSources(cwd);if(sources.length===0)return[];if(sources.some(source=>source.modules.has("index")))return[];let observed=new Set(definitions.filter(definition=>sources.some(source=>source.modules.has(definition.pascal)||source.uids.has(definition.uid))).map(d3=>d3.uid)),byUid=new Map(definitions.map(definition=>[definition.uid,definition])),pending=[...observed];for(;pending.length>0;)for(let target of byUid.get(pending.pop())?.references??[])byUid.has(target)&&!observed.has(target)&&(observed.add(target),pending.push(target));return definitions.filter(definition=>!observed.has(definition.uid)).map(definition=>({code:"content/no-observed-consumer",message:`Content type "${definition.uid}" has no observed consumer in this preview: no file outside ${SCHEMAS_DIR_REL} imports its generated client "${SCHEMAS_DIR_REL}/${definition.pascal}" or names "${definition.uid}". Its entries can be live in Fimo and never reach the site. Only this workspace was scanned (${sources.length} source ${sources.length===1?"file":"files"}), so code outside it was not inspected.`,file:definition.file,evidence:{uid:definition.uid,module:`${SCHEMAS_DIR_REL}/${definition.pascal}`,sourceFilesScanned:sources.length,scope:"workspace-static-imports"}}))}__name(findContentTypesWithoutObservedConsumer,"findContentTypesWithoutObservedConsumer");function readSourceConsumers(file,source){let consumers={modules:new Set,uids:new Set},{parseSync:parseSync3,Visitor}=require4("oxc-parser"),literal=__name(node=>{if(node?.type==="Literal"&&typeof node.value=="string")return node.value;if(node?.type==="TemplateLiteral"&&node.expressions.length===0)return node.quasis[0]?.value.cooked??void 0},"literal"),observeImport=__name(specifier=>{let match=specifier?.match(/(?:^|\/)schemas(?:\/([^/]+))?$/);match&&consumers.modules.add((match[1]??"index").replace(/\.(?:[cm]?[jt]sx?|json)$/,"").replace(/\.(?:client|server|types)$/,""))},"observeImport"),modules=[source];if(/\.(?:svelte|vue|astro)$/.test(file)){let frontmatter=file.endsWith(".astro")?source.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/):null;modules=[...source.slice(frontmatter?.[0].length??0).replace(/<!--[\s\S]*?-->/g,"").matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map(match=>match[1]),frontmatter&&modules.push(frontmatter[1])}for(let code2 of modules){let parsed=parseSync3(/\.[cm]?[jt]sx?$/.test(file)?file:`${file}.tsx`,code2);parsed.errors.length>0||new Visitor({ImportDeclaration:__name(node=>observeImport(node.source.value),"ImportDeclaration"),ExportNamedDeclaration:__name(node=>observeImport(node.source?.value),"ExportNamedDeclaration"),ExportAllDeclaration:__name(node=>observeImport(node.source.value),"ExportAllDeclaration"),ImportExpression:__name(node=>observeImport(literal(node.source)),"ImportExpression"),CallExpression:__name(node=>{node.callee.type==="Identifier"&&node.callee.name==="require"&&observeImport(literal(node.arguments[0]));for(let argument of node.arguments){let uid=literal(argument);uid&&consumers.uids.add(uid)}},"CallExpression"),MemberExpression:__name(node=>{let uid=node.computed?literal(node.property):void 0;uid&&consumers.uids.add(uid)},"MemberExpression")}).visit(parsed.program)}return consumers}__name(readSourceConsumers,"readSourceConsumers");function readSchemaDefinitions(cwd){let fileNames;try{fileNames=readdirSync7(path29.join(cwd,SCHEMAS_DIR_REL)).filter(name=>name.endsWith(".json")).sort()}catch{return[]}let definitions=[];for(let name of fileNames){let parsed;try{parsed=JSON.parse(readFileSync9(path29.join(cwd,SCHEMAS_DIR_REL,name),"utf8"))}catch{continue}let uid=path29.basename(name,".json");definitions.push({uid,pascal:pascalCase(uid),file:`${SCHEMAS_DIR_REL}/${name}`,references:collectReferenceTargets(parsed,[])})}return definitions}__name(readSchemaDefinitions,"readSchemaDefinitions");function collectReferenceTargets(node,targets){if(Array.isArray(node)){for(let item of node)collectReferenceTargets(item,targets);return targets}if(node===null||typeof node!="object")return targets;let record=node;if(record.type==="reference")for(let target of[record.target,...Array.isArray(record.targets)?record.targets:[]])typeof target=="string"&&targets.push(target);for(let value of Object.values(record))collectReferenceTargets(value,targets);return targets}__name(collectReferenceTargets,"collectReferenceTargets");function readProjectSources(cwd){let schemasDir=path29.join(cwd,SCHEMAS_DIR_REL),sources=[],walk=__name(dir=>{let entries2;try{entries2=readdirSync7(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){let full=path29.join(dir,entry.name);if(entry.isDirectory()){if(entry.name.startsWith(".")||IGNORED_SCAN_DIRS.has(entry.name)||full===schemasDir)continue;walk(full)}else if(entry.isFile()&&SOURCE_FILE_PATTERN.test(entry.name))try{sources.push(readSourceConsumers(full,readFileSync9(full,"utf8")))}catch{}}},"walk");return walk(cwd),sources}__name(readProjectSources,"readProjectSources");async function runChecksPhase(opts){let{cwd,onWarning}=opts,[lintResult,routeResult,agentsResult,schemasResult,configResult,packageManagerResult,dependencyResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd})),Promise.resolve().then(()=>validateFimoConfig(cwd)),Promise.resolve().then(()=>resolvePackageManagerContract(cwd)),Promise.resolve().then(()=>inspectDependencyLifecycleScripts(cwd))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));if(configResult.status==="fulfilled"){stats.configsChecked=Number(configResult.value.configChecked);for(let message of configResult.value.errors)errors.push(authorError({rule:"fimo-config",message}))}else errors.push(infraErrorFromException("fimo-config",configResult.reason));if(packageManagerResult.status==="fulfilled"){let contract=packageManagerResult.value;contract.status==="unresolved"&&errors.push(authorError({rule:`package-manager/${contract.violation}`,message:contract.message,file:"package.json"}))}else errors.push(infraErrorFromException("package-manager",packageManagerResult.reason));return dependencyResult.status==="fulfilled"?dependencyResult.value.status==="warning"?onWarning?.(dependencyResult.value.message):dependencyResult.value.status==="blocked"&&errors.push(authorError({rule:"dependency-build-scripts",message:`${dependencyResult.value.packageManager} blocked lifecycle scripts for: ${dependencyResult.value.packages.join(", ")}. Add these packages to the project's explicit build-script approval policy, reinstall, and re-run validation.`})):onWarning?.(`Dependency lifecycle-script approval check skipped: inspection failed (${dependencyResult.reason instanceof Error?dependencyResult.reason.message:String(dependencyResult.reason)}).`),{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");async function runRouteMetadataCheck(opts){return(await detectProjectFramework(opts.cwd))?.slug!=="react-router"?null:validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,frameworkResult=detectProjectFramework(cwd),[schemasResult,formsResult,labelsResult]=await Promise.allSettled([frameworkResult.then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),frameworkResult.then(framework=>syncForms({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,branchOverride:branchOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,branchOverride:branchOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let fimo=createCliFimoClient(loadConfig(),ctx.branch),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(async()=>(await fimo.execute("labels.list",{projectId:ctx.projectId,branch:ctx.branch,locale})).data,"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Branch":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path29.join(cwd,".env")),...await readEnvFile(path29.join(cwd,".env.local"))};if(process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),!values.VITE_API_URL){let derived=resolveLocalRuntimeEnv({cwd});derived&&(values.VITE_API_URL=derived.tenantApiUrl,values.FIMO_ENV??=derived.env)}return values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index=trimmed.indexOf("=");if(index===-1)continue;let key=trimmed.slice(0,index).trim(),value=trimmed.slice(index+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){if(process.env.FIMO_MIGRATION_NO_DEPLOY==="1"){ui.error({command:"deploy",code:"MIGRATION_DEPLOY_BLOCKED",message:"Deployment is disabled while a migration is running.",hint:"Finish local migration and QA first, then request deployment separately."});return}let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let branchOverride2=branchOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,branchOverride:branchOverride2});if(isPretty2&&process.stderr.write(`${branchSourceBanner(ctx)}
|
|
636
636
|
`),ctx.readOnly){ui.error({command:"deploy",code:"BRANCH_READONLY",message:`Refusing to deploy to read-only Branch '${ctx.branch}'.`,hint:"Switch off the release/* tag or pass --branch <writable-branch>."});return}let cfg=loadConfig(),fimo=createCliFimoClient(cfg,ctx.branch),git=createGitService(cfg,ctx.branch),sandbox=createSandboxService(cfg,ctx.branch),publication=createPublicationControlService(cfg,ctx.branch),studioUrl=buildProjectPreviewUrl(cfg.webUrl,local.projectId,ctx.branch),{data:project}=await fimo.execute("projects.get",{projectId:local.projectId}),productionSourceBranch=project.productionSourceBranch??DEFAULT_BRANCH,previewEnabled=project.previewEnabled!==!1;if(options.publish&&ctx.branch!==productionSourceBranch){ui.error({command:"deploy",code:"PUBLISH_REQUIRES_SOURCE_BRANCH",message:`Refusing to --publish from Branch '${ctx.branch}'. Production publishes from '${productionSourceBranch}'.`,hint:`Drop --publish to deploy a preview, or switch to '${productionSourceBranch}' first.`});return}let devFimoSelection;try{devFimoSelection=resolveDevFimoDependencyForDeploy(cwd)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}await requireOperation("fimo.deploy",{projectId:ctx.projectId,branch:ctx.branch});let remoteSp=spinner("Checking the Fimo branch"),remote;try{remote=await git.getRemote(local.projectId,ctx.branch),await ensureFimoRemote(cwd,remote.url);let preparation=await prepareDeployCheckout({cwd,remoteBranch:remote.branch});remoteSp.succeed(preparation==="missing-remote"?`Fimo branch ${remote.branch} will be created by this deploy`:`Checkout ready for fimo/${remote.branch}`)}catch(error){if(remoteSp.fail("Checkout is not ready to deploy"),error instanceof BranchCheckoutError){ui.error({command:"deploy",code:error.code,message:error.message,hint:error.hint});return}rethrowCliAuthError(error),ui.error({command:"deploy",code:"ENV_GIT_PREFLIGHT_FAILED",message:`Could not compare this checkout with the Fimo branch: ${errorMessage(error)}`});return}let validateSp=spinner("Validating project"),report=await runValidate({cwd,branchOverride:branchOverride2});if(report.ok){validateSp.succeed("Validation passed");let packageManagerWarning=getPackageManagerPinWarning(cwd);packageManagerWarning&&ui.warn({command:"deploy",message:packageManagerWarning})}else if(options.force)validateSp.fail("Validation failed \u2014 continuing anyway (--force)"),ui.warn({command:"deploy",message:"Bypassing validation errors because --force was passed. The deploy may still fail later in the sandbox."});else{validateSp.fail("Validation failed"),ui.result({command:"deploy",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}let devFimoDependency=null;try{devFimoDependency=prepareDevFimoDependencyForDeploy(cwd,devFimoSelection)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}devFimoDependency&&isPretty2&&O2.info(`Deploying with fimo ${devFimoDependency.version}; restoring local dependency state after push.`);try{if(await hasUncommittedChanges(cwd)){let message;if(options.message!==void 0)message=options.message;else{assertInteractive('Pass -m "<message>" or commit your changes manually.',"deploy"),isPretty2&&O2.warn("You have uncommitted changes. Commit them before deploying.");let answer=await Ot({message:"Commit message",placeholder:"Deploy",defaultValue:"Deploy"});if(q(answer)){ui.info({command:"deploy",message:"Cancelled."});return}message=String(answer)}let commitSp=spinner("Committing pending changes");await runGit(["add","-A"],cwd),await runGit(["commit","-m",message],cwd),commitSp.succeed("Changes committed")}let remoteBranch=remote.branch,pushSp=spinner(`Pushing to fimo/${remoteBranch}`);try{await runGit(["push","fimo",`HEAD:${remoteBranch}`],cwd),pushSp.succeed("Pushed to Fimo")}catch(error){pushSp.fail("Push failed");let failure=classifyPushError(error);emitPushFailure(failure,remoteBranch);return}}finally{devFimoDependency?.restore()}let stepLabel="",stepStartedAt=0,stepSp=null,finalizeStep=__name((status="ok",failMessage)=>{if(!stepSp)return;let elapsed=((Date.now()-stepStartedAt)/1e3).toFixed(1);status==="ok"?stepSp.succeed(`${stepLabel} (${elapsed}s)`):stepSp.fail(failMessage??`${stepLabel} failed`),stepSp=null},"finalizeStep");try{await sandbox.pull(local.projectId,({message})=>{finalizeStep("ok"),stepLabel=message,stepStartedAt=Date.now(),stepSp=spinner(message)},ctx.branch,{noRestart:options.restart===!1,wait:options.wait!==!1}),finalizeStep("ok")}catch(error){if(rethrowCliAuthError(error,()=>finalizeStep("fail","Authentication required")),error instanceof SandboxPullError){let failure=describeDeployFailure(error.failure,isPretty2);finalizeStep("fail",failure.step),ui.error({command:"deploy",...failure.envelope});return}finalizeStep("fail",`Sandbox sync failed: ${errorMessage(error)}`),ui.error({command:"deploy",code:"SANDBOX_SYNC_FAILED",message:`Sandbox sync failed: ${errorMessage(error)}`});return}if(!options.publish){ui.result({command:"deploy",data:{project_id:local.projectId,branch:ctx.branch,preview_enabled:previewEnabled,studio_url:studioUrl,dashboard_url:studioUrl,published:!1},render:__name(context=>renderDeployResult({studioUrl,appUrl:null,previewEnabled,published:!1},context),"render")});return}let publishSp=spinner("Publishing (this can take a few minutes)"),publicationId;try{publicationId=await publication.publish(local.projectId)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail();let failedPublicationId=publicationIdFromError(error);ui.error({command:"deploy",code:"PUBLISH_FAILED",message:`Publish failed: ${errorMessage(error)}`,...failedPublicationId?{details:{publication_id:failedPublicationId},hint:`Run \`fimo publish logs ${failedPublicationId}\` for the build output that failed.`}:{}});return}publishSp.succeed("Published");let appUrl=null;try{let{data:fresh}=await fimo.execute("projects.get",{projectId:local.projectId});appUrl=fresh.appUrl??null}catch(error){isPretty2&&O2.warn(`Could not fetch published URL: ${errorMessage(error)}`)}ui.result({command:"deploy",data:{project_id:local.projectId,branch:ctx.branch,preview_enabled:previewEnabled,studio_url:studioUrl,dashboard_url:studioUrl,published:!0,publication_id:publicationId,app_url:appUrl},render:__name(context=>renderDeployResult({studioUrl,appUrl,previewEnabled,published:!0},context),"render")})}__name(deployCommand,"deployCommand");var PHASE_LABELS={acquire:"acquiring the preview sandbox",pull:"pulling the Fimo branch into the preview sandbox","sync-env":"syncing the Branch environment into the preview sandbox",install:"installing dependencies",restart:"starting the dev server",readiness:"waiting for the preview to become ready"},RETRY_HINT="Run `fimo deploy` again. If it keeps failing, report it with `fimo support report`.";function deployFailureHint(failure){return failure.repair?`Review the listed packages, approve them through ${failure.repair.configFile}#${failure.repair.approvalKey}, commit the policy and lockfile, then run \`fimo deploy\` again. Never enable a global allow-all switch.`:failure.phase==="install"?"Reproduce with a clean install locally using the project's package manager, fix package.json and the lockfile so it passes, commit them, then run `fimo deploy` again.":failure.phase==="restart"?"Run the project's dev script locally to reproduce the startup error above, fix it, then run `fimo deploy` again.":failure.phase==="pull"?"Run `fimo deploy` again. If the pull keeps failing, report it with `fimo support report` and include the output above.":failure.phase==="readiness"||failure.code==="readiness_failed"?failure.logTail?.length?"Fix what the dev server reported above, then run `fimo deploy` again. Pass --no-wait to deploy without this check.":"Run `fimo logs` to see what the dev server reported, fix it, then deploy again. Pass --no-wait to deploy without this check.":RETRY_HINT}__name(deployFailureHint,"deployFailureHint");function describeDeployFailure(failure,isPretty2){let label=failure.phase?PHASE_LABELS[failure.phase]:null,exit=failure.exitCode!==void 0?` (exit code ${failure.exitCode})`:"",code2=failure.code==="readiness_failed"?"PREVIEW_NOT_READY":"SANDBOX_SYNC_FAILED",message;label?code2==="PREVIEW_NOT_READY"?message=`The revision was synced, but the preview never became ready. Failed while ${label}${exit}: ${failure.message}`:message=`Deploy failed while ${label}${exit}: ${failure.message}`:message=code2==="PREVIEW_NOT_READY"?`The revision was synced, but the preview never became ready: ${failure.message}`:`Sandbox sync failed: ${failure.message}`;let tail=failure.logTail??[];if(isPretty2&&tail.length>0){let heading=`Last ${tail.length} lines from the sandbox${failure.logTailTruncated?" (older output cut)":""}:`;message=[message,heading,...tail.map(line=>` ${line}`)].join(`
|
|
637
637
|
`)}let details={...failure.code?{failure_code:failure.code}:{},...failure.phase?{phase:failure.phase}:{},...failure.exitCode!==void 0?{exit_code:failure.exitCode}:{},...failure.logTail?{log_tail:failure.logTail,log_tail_truncated:failure.logTailTruncated===!0}:{},...failure.repair?{repair:failure.repair}:{}},hint=label||failure.repair||code2==="PREVIEW_NOT_READY"?deployFailureHint(failure):void 0;return{step:label?`Failed while ${label}${exit}`:code2==="PREVIEW_NOT_READY"?`Preview did not become ready: ${failure.message}`:`Sandbox sync failed: ${failure.message}`,envelope:{code:code2,message,...hint?{hint}:{},...Object.keys(details).length>0?{details}:{}}}}__name(describeDeployFailure,"describeDeployFailure");function renderDeployResult(result,context){let lines=[];return result.appUrl&&lines.push(`Live: ${terminalLink("Open site",result.appUrl,context.hyperlinks)}`),lines.push(`Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),result.published?lines.push(result.appUrl?"Your site is live.":"Publish completed. Check Fimo for the live URL."):lines.push(result.previewEnabled?"Deployed. Run `fimo preview url` for the hosted preview, or `fimo deploy --publish` to publish.":"Changes synced. Preview is disabled for this project."),lines.join(`
|
|
638
638
|
`)}__name(renderDeployResult,"renderDeployResult");function emitPushFailure(failure,env){switch(failure.kind){case"non-fast-forward":ui.error({command:"deploy",code:"PUSH_NON_FAST_FORWARD",message:`The remote \`fimo/${env}\` has commits your local branch does not.`,hint:`Fix it manually, then re-run \`fimo deploy\`:
|
|
@@ -667,7 +667,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
667
667
|
Purchase: ${formatPrice(pricing.price)} \xD7 ${effectiveYears} year${effectiveYears===1?"":"s"} = ${formatPrice(totalCents)}
|
|
668
668
|
Renewal: ${formatPrice(pricing.renewalPrice)}/year${autoRenew===!1?" (auto-renew off)":" (auto-renews)"}`);let confirmed=await ot2({message:`Create a checkout invoice for ${domain}?`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"domains buy",message:"Cancelled."});return}}let purchased;try{purchased=await fimo.execute("registeredDomains.purchase",{organizationId,domain,years:effectiveYears,autoRenew})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains buy",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError){if(err.status===403){ui.error({command:"domains buy",code:"PURCHASE_FORBIDDEN",message:"You don't have permission to buy domains for this organization.",hint:"Org admins only."});return}ui.error({command:"domains buy",code:"PURCHASE_FAILED",message:`Purchase failed: ${err.detail}`});return}throw err}ui.result({command:"domains buy",data:purchased,render:__name(()=>{let lines=[];return lines.push(""),lines.push(`Invoice created for ${purchased.domain} (${formatPrice(purchased.price)}).`),lines.push("Pay to complete registration:"),lines.push(""),lines.push(` ${purchased.checkoutUrl??"(checkout URL pending \u2014 refresh in a moment)"}`),lines.push(""),lines.push("No money moves until you complete payment in the browser."),lines.push(`Once paid, ${purchased.domain} registers automatically and shows up in \`fimo domains owned\`.`),lines.join(`
|
|
669
669
|
`)},"render")}),options.open&&purchased.checkoutUrl&&await open_default(purchased.checkoutUrl).catch(()=>{});let{enabled:waitEnabled,timeoutMs}=parseWait(options,!1);waitEnabled&&await pollPurchasePayment(fimo,organizationId,purchased,timeoutMs)}__name(domainsBuyCommand,"domainsBuyCommand");async function pollPurchasePayment(fimo,organizationId,initial,timeoutMs){let start=Date.now(),sp=spinner(`Waiting for payment (status: ${initial.status})`),current=initial;for(;Date.now()-start<timeoutMs;){if(current.status==="owned")return sp.succeed(`Registered \u2014 ${current.domain} is now yours.`),current;if(current.status==="registration_failed"||current.status==="payment_failed")return sp.fail(`${current.status==="payment_failed"?"Payment":"Registration"} failed for ${current.domain}.`),current;await new Promise(resolve10=>setTimeout(resolve10,5e3));try{current=await fimo.execute("registeredDomains.refreshPayment",{organizationId,domainId:current.id}),sp.update(`Waiting (status: ${current.status})`)}catch(err){return rethrowCliAuthError(err,()=>sp.fail("Authentication required")),sp.fail(`Refresh failed: ${err instanceof Error?err.message:String(err)}`),current}}return sp.fail("Timed out. Run `fimo domains owned` later to check status."),current}__name(pollPurchasePayment,"pollPurchasePayment");async function domainsOwnedCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),organizationId=resolveOrgId(options),domains2;try{domains2=await fimo.execute("registeredDomains.list",{organizationId})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains owned",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError&&err.status===403){ui.error({command:"domains owned",code:"OWNED_DOMAINS_FORBIDDEN",message:"You don't have access to this organization's domains.",hint:"Org admins only."});return}throw err}let statusFilter=options.status?.split(",").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0),limit=options.limit?parseInt(options.limit,10):null,filtered=domains2;if(statusFilter&&statusFilter.length>0&&(filtered=filtered.filter(d3=>statusFilter.includes(d3.status.toLowerCase()))),limit!==null&&Number.isFinite(limit)&&limit>0&&(filtered=filtered.slice(0,limit)),filtered.length===0){ui.info({command:"domains owned",message:"No domains registered through Fimo yet.",hint:"Try `fimo domains search <keyword>`."});return}ui.result({command:"domains owned",data:{domains:filtered,total:filtered.length},render:__name(()=>{let nameW=Math.max(8,...filtered.map(d3=>d3.domain.length)),statusW=Math.max(8,...filtered.map(d3=>d3.status.length)),lines=[];lines.push(` ${pad("DOMAIN",nameW)} ${pad("STATUS",statusW)} EXPIRES`);for(let d3 of filtered){let expires=d3.expirationDate?new Date(d3.expirationDate).toISOString().slice(0,10):"\u2014";lines.push(` ${pad(d3.domain,nameW)} ${pad(d3.status,statusW)} ${expires}`)}return lines.join(`
|
|
670
|
-
`)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_config();init_sdk_transport();init_project_context();init_project();import fs32 from"node:fs";import path32 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path32.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs32.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}},DEFAULT_BULK_CHUNK_SIZE=100,MAX_BULK_CHUNK_SIZE=1e3;function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseChunkSize(value){if(value===void 0)return DEFAULT_BULK_CHUNK_SIZE;let size=Number(value);if(!Number.isInteger(size)||size<1||size>MAX_BULK_CHUNK_SIZE)throw new EntriesInputError(`--chunk-size must be an integer from 1 to ${MAX_BULK_CHUNK_SIZE}.`);return size}__name(parseChunkSize,"parseChunkSize");function chunksOf(items,size){let chunks=[];for(let offset=0;offset<items.length;offset+=size)chunks.push(items.slice(offset,offset+size));return chunks}__name(chunksOf,"chunksOf");function parseEntryInput(value,index){if(!value||typeof value!="object"||Array.isArray(value))throw new EntriesInputError(`Entry ${index+1} must be a JSON object.`);let input=value;if(!input.data||typeof input.data!="object"||Array.isArray(input.data))throw new EntriesInputError(`Entry ${index+1} must include a data object.`);return input}__name(parseEntryInput,"parseEntryInput");function identityValue(input,field,index){let value=field==="slug"?input.data.slug??input.data[field]:input.data[field];if(typeof value!="string"||value.length===0)throw new EntriesInputError(`Entry ${index+1} needs a non-empty data.${field} for --upsert-by ${field}.`);return value}__name(identityValue,"identityValue");function identityKey(value,locale){return`${locale??""}\0${value}`}__name(identityKey,"identityKey");async function listEntriesByIdentity(content2,projectId,typeName,field,inputs){let byLocale=new Map;for(let[index,input]of inputs.entries()){let values=byLocale.get(input.locale)??new Set;values.add(identityValue(input,field,index)),byLocale.set(input.locale,values)}let found=new Map;for(let[locale,values]of byLocale){let result=await content2.listEntries(projectId,typeName,{limit:"100",where:JSON.stringify({[field]:{$in:[...values]}}),fields:`id,documentId,${field},locale`,...locale?{locale}:{}});if(result.meta.hasMore)throw new EntriesInputError(`More than 100 ${typeName} entries matched this ${field} batch; reduce --chunk-size.`);for(let entry of result.data){let value=entry[field];if(typeof value!="string")continue;let key=identityKey(value,locale);found.set(key,[...found.get(key)??[],entry])}}return found}__name(listEntriesByIdentity,"listEntriesByIdentity");async function createWithReconciliation(fimo,content2,projectId,branch,typeName,field,inputs){let pending=inputs,created=0,reconciled=0;for(let attempt=0;attempt<2&&pending.length>0;attempt+=1)try{let result=await fimo.execute("entries.bulkCreate",{projectId,branch,typeName,entries:pending});created+=result.meta.created,pending=[]}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;let existing=await listEntriesByIdentity(content2,projectId,typeName,field,pending),absent=pending.filter((input,index)=>{let key=identityKey(identityValue(input,field,index),input.locale);return(existing.get(key)?.length??0)===0});reconciled+=pending.length-absent.length,pending=absent}if(pending.length>0)throw new EntriesInputError(`${pending.length} entries remain absent after reconciling an ambiguous 504; rerun the same upsert input safely.`);return{created,reconciled}}__name(createWithReconciliation,"createWithReconciliation");async function upsertChunk(fimo,content2,projectId,branch,typeName,field,inputs,chunk,identityCounts){let existing=await listEntriesByIdentity(content2,projectId,typeName,field,inputs),creates=[],updates=[],conflicts=0;for(let[index,input]of inputs.entries()){let key=identityKey(identityValue(input,field,index),input.locale),matches=existing.get(key)??[];if((identityCounts.get(key)??0)>1||matches.length>1){conflicts+=1;continue}matches.length===1?updates.push({id:matches[0].documentId,body:input}):creates.push(input)}let updated=0;if(updates.length>0)try{let result=await fimo.execute("entries.bulkUpdate",{projectId,branch,typeName,selection:{updates}});updated=result.meta.updated,conflicts+=result.meta.missing.length}catch(error){throw!(error instanceof ApiRequestError)||error.status!==504?error:(await listEntriesByIdentity(content2,projectId,typeName,field,inputs),new EntriesInputError(`${updates.length} updates had an ambiguous 504; identities were reread without replay. Rerun the same upsert input safely.`))}let createResult=await createWithReconciliation(fimo,content2,projectId,branch,typeName,field,creates);return{chunk,input:inputs.length,created:createResult.created,updated,conflicts,reconciled:createResult.reconciled}}__name(upsertChunk,"upsertChunk");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch});let params={};params.limit=String(pagination.limit),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);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});return toOffsetPaginationPage(await content2.listEntries(ctx.projectId,typeName,{...params,offset:String(offset)}))},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=paginationTrailingArgs(options,ctx.branch);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","entries","list",typeName],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(entriesListCommand,"entriesListCommand");function paginationTrailingArgs(options,branch){return[["--branch",branch],["--search",options.search],["--sort",options.sort],["--sort-by",options.sortBy],["--sort-direction",options.sortDirection],["--where",options.where],["--fields",options.fields],["--populate",options.populate],["--locale",options.locale],["--cwd",options.cwd]].flatMap(([flag2,value])=>value===void 0?[]:[flag2,value])}__name(paginationTrailingArgs,"paginationTrailingArgs");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale});ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,branch:ctx.branch});let input=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),{data:result}=await fimo.execute("entries.create",{projectId:ctx.projectId,branch:ctx.branch,typeName,...input});ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let data=parseJsonObject(options.body),result=await fimo.execute("entries.updateFields",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale,fields:data});ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.delete",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale});ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,branch:ctx.branch});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await fimo.execute("entries.querySql",{projectId:ctx.projectId,branch:ctx.branch,sql});ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.bulk_create",{projectId:ctx.projectId,branch:ctx.branch}),options.upsertBy&&(await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch}));let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))),chunkSize=parseChunkSize(options.chunkSize);if(entries2.length===0){if(options.upsertBy)throw new EntriesInputError("Upsert input must be a non-empty JSON array.");let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:entries2});ui.result({command:"entries bulk-create",data:result2,render:__name(()=>renderPrettyJson5(result2),"render")});return}let upsertInputs=options.upsertBy?entries2.map((entry,index)=>parseEntryInput(entry,index)):[],identityCounts=new Map;if(options.upsertBy)for(let[index,input]of upsertInputs.entries()){let key=identityKey(identityValue(input,options.upsertBy,index),input.locale);identityCounts.set(key,(identityCounts.get(key)??0)+1)}let chunks=chunksOf(options.upsertBy?upsertInputs:entries2,chunkSize),receipts=[],data=[];for(let[index,chunk]of chunks.entries()){if(options.upsertBy){receipts.push(await upsertChunk(fimo,content2,ctx.projectId,ctx.branch,typeName,options.upsertBy,chunk,index+1,identityCounts));continue}let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:chunk});data.push(...result2.data),receipts.push({chunk:index+1,input:chunk.length,created:result2.meta.created,updated:0,conflicts:0,reconciled:0})}let result={data,meta:{created:receipts.reduce((sum,receipt)=>sum+receipt.created,0),updated:receipts.reduce((sum,receipt)=>sum+receipt.updated,0),conflicts:receipts.reduce((sum,receipt)=>sum+receipt.conflicts,0),chunks:receipts}};ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch});let usesBatchInput=!!(options.file||options.stdin),selection,body;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");selection={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)))}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body=parseBulkJsonObject(options.body)}let result=await fimo.execute("entries.bulkUpdate",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,body});ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,branch:ctx.branch}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},result=await fimo.execute("entries.bulkDelete",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,locale:options.locale});ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_config();init_sdk_transport();init_project();function collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions(command){return command.option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions,"addScopeOptions");function registerEnvironmentsCommands(program2){let environments=program2.command("environments").description("Group project Branches into deployment Environments").addHelpText("after",`
|
|
670
|
+
`)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_config();init_sdk_transport();init_project_context();init_project();import fs32 from"node:fs";import path32 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path32.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs32.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}};function reportSingleContentTypeError(command,error){return!(error instanceof ApiRequestError)||error.code!=="single_content_type"?!1:(ui.error({command,code:"SINGLE_CONTENT_TYPE",message:"This content type is a Single. Use `fimo singles update` to create or update it."}),!0)}__name(reportSingleContentTypeError,"reportSingleContentTypeError");var DEFAULT_BULK_CHUNK_SIZE=100,MAX_BULK_CHUNK_SIZE=1e3;function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseChunkSize(value){if(value===void 0)return DEFAULT_BULK_CHUNK_SIZE;let size=Number(value);if(!Number.isInteger(size)||size<1||size>MAX_BULK_CHUNK_SIZE)throw new EntriesInputError(`--chunk-size must be an integer from 1 to ${MAX_BULK_CHUNK_SIZE}.`);return size}__name(parseChunkSize,"parseChunkSize");function chunksOf(items,size){let chunks=[];for(let offset=0;offset<items.length;offset+=size)chunks.push(items.slice(offset,offset+size));return chunks}__name(chunksOf,"chunksOf");function parseEntryInput(value,index){if(!value||typeof value!="object"||Array.isArray(value))throw new EntriesInputError(`Entry ${index+1} must be a JSON object.`);let input=value;if(!input.data||typeof input.data!="object"||Array.isArray(input.data))throw new EntriesInputError(`Entry ${index+1} must include a data object.`);return input}__name(parseEntryInput,"parseEntryInput");function identityValue(input,field,index){let value=field==="slug"?input.data.slug??input.data[field]:input.data[field];if(typeof value!="string"||value.length===0)throw new EntriesInputError(`Entry ${index+1} needs a non-empty data.${field} for --upsert-by ${field}.`);return value}__name(identityValue,"identityValue");function identityKey(value,locale){return`${locale??""}\0${value}`}__name(identityKey,"identityKey");async function listEntriesByIdentity(content2,projectId,typeName,field,inputs){let byLocale=new Map;for(let[index,input]of inputs.entries()){let values=byLocale.get(input.locale)??new Set;values.add(identityValue(input,field,index)),byLocale.set(input.locale,values)}let found=new Map;for(let[locale,values]of byLocale){let result=await content2.listEntries(projectId,typeName,{limit:"100",where:JSON.stringify({[field]:{$in:[...values]}}),fields:`id,documentId,${field},locale`,...locale?{locale}:{}});if(result.meta.hasMore)throw new EntriesInputError(`More than 100 ${typeName} entries matched this ${field} batch; reduce --chunk-size.`);for(let entry of result.data){let value=entry[field];if(typeof value!="string")continue;let key=identityKey(value,locale);found.set(key,[...found.get(key)??[],entry])}}return found}__name(listEntriesByIdentity,"listEntriesByIdentity");async function createWithReconciliation(fimo,content2,projectId,branch,typeName,field,inputs){let pending=inputs,created=0,reconciled=0;for(let attempt=0;attempt<2&&pending.length>0;attempt+=1)try{let result=await fimo.execute("entries.bulkCreate",{projectId,branch,typeName,entries:pending});created+=result.meta.created,pending=[]}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;let existing=await listEntriesByIdentity(content2,projectId,typeName,field,pending),absent=pending.filter((input,index)=>{let key=identityKey(identityValue(input,field,index),input.locale);return(existing.get(key)?.length??0)===0});reconciled+=pending.length-absent.length,pending=absent}if(pending.length>0)throw new EntriesInputError(`${pending.length} entries remain absent after reconciling an ambiguous 504; rerun the same upsert input safely.`);return{created,reconciled}}__name(createWithReconciliation,"createWithReconciliation");async function upsertChunk(fimo,content2,projectId,branch,typeName,field,inputs,chunk,identityCounts){let existing=await listEntriesByIdentity(content2,projectId,typeName,field,inputs),creates=[],updates=[],conflicts=0;for(let[index,input]of inputs.entries()){let key=identityKey(identityValue(input,field,index),input.locale),matches=existing.get(key)??[];if((identityCounts.get(key)??0)>1||matches.length>1){conflicts+=1;continue}matches.length===1?updates.push({id:matches[0].documentId,body:input}):creates.push(input)}let updated=0;if(updates.length>0)try{let result=await fimo.execute("entries.bulkUpdate",{projectId,branch,typeName,selection:{updates}});updated=result.meta.updated,conflicts+=result.meta.missing.length}catch(error){throw!(error instanceof ApiRequestError)||error.status!==504?error:(await listEntriesByIdentity(content2,projectId,typeName,field,inputs),new EntriesInputError(`${updates.length} updates had an ambiguous 504; identities were reread without replay. Rerun the same upsert input safely.`))}let createResult=await createWithReconciliation(fimo,content2,projectId,branch,typeName,field,creates);return{chunk,input:inputs.length,created:createResult.created,updated,conflicts,reconciled:createResult.reconciled}}__name(upsertChunk,"upsertChunk");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch});let params={};params.limit=String(pagination.limit),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);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});return toOffsetPaginationPage(await content2.listEntries(ctx.projectId,typeName,{...params,offset:String(offset)}))},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=paginationTrailingArgs(options,ctx.branch);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","entries","list",typeName],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(entriesListCommand,"entriesListCommand");function paginationTrailingArgs(options,branch){return[["--branch",branch],["--search",options.search],["--sort",options.sort],["--sort-by",options.sortBy],["--sort-direction",options.sortDirection],["--where",options.where],["--fields",options.fields],["--populate",options.populate],["--locale",options.locale],["--cwd",options.cwd]].flatMap(([flag2,value])=>value===void 0?[]:[flag2,value])}__name(paginationTrailingArgs,"paginationTrailingArgs");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale,populate:options.populate?[options.populate]:void 0});ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,branch:ctx.branch});let input=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),{data:result}=await fimo.execute("entries.create",{projectId:ctx.projectId,branch:ctx.branch,typeName,...input});ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let data=parseJsonObject(options.body),result=await fimo.execute("entries.updateFields",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale,fields:data});ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.delete",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale});ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,branch:ctx.branch});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await fimo.execute("entries.querySql",{projectId:ctx.projectId,branch:ctx.branch,sql});ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.bulk_create",{projectId:ctx.projectId,branch:ctx.branch}),options.upsertBy&&(await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch}));let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))),chunkSize=parseChunkSize(options.chunkSize);if(entries2.length===0){if(options.upsertBy)throw new EntriesInputError("Upsert input must be a non-empty JSON array.");let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:entries2});ui.result({command:"entries bulk-create",data:result2,render:__name(()=>renderPrettyJson5(result2),"render")});return}let upsertInputs=options.upsertBy?entries2.map((entry,index)=>parseEntryInput(entry,index)):[],identityCounts=new Map;if(options.upsertBy)for(let[index,input]of upsertInputs.entries()){let key=identityKey(identityValue(input,options.upsertBy,index),input.locale);identityCounts.set(key,(identityCounts.get(key)??0)+1)}let chunks=chunksOf(options.upsertBy?upsertInputs:entries2,chunkSize),receipts=[],data=[];for(let[index,chunk]of chunks.entries()){if(options.upsertBy){receipts.push(await upsertChunk(fimo,content2,ctx.projectId,ctx.branch,typeName,options.upsertBy,chunk,index+1,identityCounts));continue}let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:chunk});data.push(...result2.data),receipts.push({chunk:index+1,input:chunk.length,created:result2.meta.created,updated:0,conflicts:0,reconciled:0})}let result={data,meta:{created:receipts.reduce((sum,receipt)=>sum+receipt.created,0),updated:receipts.reduce((sum,receipt)=>sum+receipt.updated,0),conflicts:receipts.reduce((sum,receipt)=>sum+receipt.conflicts,0),chunks:receipts}};ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch});let usesBatchInput=!!(options.file||options.stdin),selection,body;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");selection={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)))}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body=parseBulkJsonObject(options.body)}let result=await fimo.execute("entries.bulkUpdate",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,body});ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,branch:ctx.branch}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},result=await fimo.execute("entries.bulkDelete",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,locale:options.locale});ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_config();init_sdk_transport();init_project();function collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions(command){return command.option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions,"addScopeOptions");function registerEnvironmentsCommands(program2){let environments=program2.command("environments").description("Group project Branches into deployment Environments").addHelpText("after",`
|
|
671
671
|
Environments group Branches. Production is the deployed snapshot published from the configured Production source.
|
|
672
672
|
Automatic previews receives every unclaimed Branch.
|
|
673
673
|
|
|
@@ -704,7 +704,7 @@ Examples:
|
|
|
704
704
|
fimo inbox list --topic agent_question --unread
|
|
705
705
|
fimo inbox get <notification-id>
|
|
706
706
|
fimo inbox answer <notification-id> --body '{"answers":[{"stepId":"direction","selected":["Editorial studio"],"note":"Keep it calm."},{"stepId":"access","selected":[]}]}'
|
|
707
|
-
`);addScopeOptions3(addPaginationOptions(inbox.command("list").description("List notifications, unread first").option("--topic <topic>",`Only one topic (${WORK_NOTIFICATION_TOPICS.join(", ")})`).option("--unread","Only unread notifications").option("--archived","Only archived notifications"),{defaultLimit:20,maxLimit:100})).action((options,command)=>inboxListCommand(options,command)),addScopeOptions3(inbox.command("get <notificationId>").description("Show one notification, with the stored form when it is a question")).action((notificationId,options,command)=>inboxGetCommand(notificationId,options,command)),addScopeOptions3(inbox.command("answer <notificationId>").description("Answer the question a notification points at, continuing the run that asked").option("--body <json>",'Compact answer JSON: {"answers":[{"stepId":"\u2026","selected":[\u2026],"note":"\u2026"}]}').option("--file <path>","Read the compact answer JSON from a file").option("--stdin","Read the compact answer JSON from stdin")).action((notificationId,options,command)=>inboxAnswerCommand(notificationId,options,command))}__name(registerInboxCommands,"registerInboxCommands");function addScopeOptions3(command){return command.option("--project <id>","Project id (defaults to the linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions3,"addScopeOptions");async function inboxListCommand(options,command){await runInboxCommand("inbox list",async()=>{let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100}),topic=parseTopic(options.topic),{fimo,projectId}=await resolveInboxScope(options,command),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(cursor=>fetchInboxPage(fimo,projectId,{cursor,limit:pagination.limit,topic,unreadOnly:options.unread===!0,archived:options.archived===!0}),"fetchPage")}),result={items:page.items,nextCursor:page.nextCursor,unreadCount:page.unreadCount},hint=page.nextCursor?buildInboxListHint(page.nextCursor,pagination.limit,options):void 0;ui.result({command:"inbox list",data:result,render:__name(()=>renderInboxList(result),"render"),...hint?{hint}:{}})})}__name(inboxListCommand,"inboxListCommand");async function inboxGetCommand(notificationId,options,command){await runInboxCommand("inbox get",async()=>{let{fimo,projectId}=await resolveInboxScope(options,command),view=await fimo.execute("notifications.get",{projectId,notificationId}),question=view.subject.kind==="question"?await fimo.execute("questions.get",{projectId,questionId:view.subject.questionId}):null,result={notification:toListItem(view),question:question?toQuestionView(question):null};ui.result({command:"inbox get",data:result,render:__name(()=>renderInboxItem(result,notificationId),"render")})})}__name(inboxGetCommand,"inboxGetCommand");async function inboxAnswerCommand(notificationId,options,command){await runInboxCommand("inbox answer",async()=>{let compact=parseCompactAnswer(await readContentInputSource(options,message=>new InboxAnswerError(message))),{fimo,projectId}=await resolveInboxScope(options,command),view=await fimo.execute("notifications.get",{projectId,notificationId});if(view.subject.kind!=="question")throw new InboxCommandError("INBOX_NOT_A_QUESTION",`This notification is a ${topicLabel(view.notification.payload.topic).toLowerCase()}, not a question, so there is nothing to answer.`,"Run `fimo inbox list --topic agent_question` to find the questions waiting on an answer.");let question=await fimo.execute("questions.get",{projectId,questionId:view.subject.questionId});if(question.state!=="open")throw new InboxCommandError("INBOX_QUESTION_CLOSED",`This question is ${question.state} and cannot be answered again.`,"Run `fimo inbox get <notification-id>` to read the answer already on record.");let answer=buildQuestionAnswer(question.request.block,compact),submitted=await fimo.execute("questions.answer",{projectId,questionId:view.subject.questionId,answer}),result={notification:toListItem(view),state:submitted.question.state,answer:answeredSteps(submitted.question),capabilities:capabilityDecision(submitted.question),replay:submitted.deduped};ui.result({command:"inbox answer",data:result,render:__name(()=>renderInboxAnswer(result),"render")})})}__name(inboxAnswerCommand,"inboxAnswerCommand");var API_ERROR_CODES={notification_not_found:"INBOX_NOT_FOUND",question_not_found:"INBOX_NOT_FOUND",question_not_open:"INBOX_QUESTION_CLOSED",question_answer_mismatch:"INBOX_ANSWER_INVALID",invalid_notification_cursor:"INBOX_INVALID_CURSOR"};async function runInboxCommand(command,operation){try{await operation()}catch(error){if(error instanceof InboxCommandError||error instanceof InboxAnswerError){ui.error({command,code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}});return}if(error instanceof ApiRequestError){ui.error({command,code:API_ERROR_CODES[error.code??""]??"INBOX_REQUEST_FAILED",message:error.detail});return}throw error}}__name(runInboxCommand,"runInboxCommand");async function resolveInboxScope(options,command){let fimo=createCliFimoClient(loadConfig());if(options.project)return{fimo,projectId:options.project};let ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverrideFromCommand(command)});return{fimo,projectId:ctx.projectId}}__name(resolveInboxScope,"resolveInboxScope");function parseTopic(value){if(value!==void 0){if(!WORK_NOTIFICATION_TOPICS.includes(value))throw new InboxCommandError("INBOX_UNKNOWN_TOPIC",`'${value}' is not an Inbox topic.`,`Topics: ${WORK_NOTIFICATION_TOPICS.join(", ")}.`);return value}}__name(parseTopic,"parseTopic");function encodeInboxCursor(cursor){return Buffer.from(JSON.stringify(cursor)).toString("base64url")}__name(encodeInboxCursor,"encodeInboxCursor");function decodeInboxCursor(raw){if(raw===void 0)return{unread:!0};try{let parsed=JSON.parse(Buffer.from(raw,"base64url").toString());if(typeof parsed.unread!="boolean"||parsed.after!==void 0&&typeof parsed.after!="string")throw new Error("unreadable cursor");return{unread:parsed.unread,...parsed.after!==void 0?{after:parsed.after}:{}}}catch{throw new InboxCommandError("INBOX_INVALID_CURSOR","The list cursor is not readable.","Pass the `nextCursor` from the previous page, or start over without --cursor.")}}__name(decodeInboxCursor,"decodeInboxCursor");async function fetchInboxPage(fimo,projectId,input){let query={...input.topic?{topic:input.topic}:{},...input.archived?{archived:!0}:{}},start=decodeInboxCursor(input.cursor),first=await fimo.execute("notifications.list",{projectId,...query,unread:start.unread,limit:input.limit,...start.after!==void 0?{cursor:start.after}:{}}),items=first.items.map(toListItem);if(first.nextCursor)return{items,nextCursor:encodeInboxCursor({unread:start.unread,after:first.nextCursor}),unreadCount:first.unreadCount};if(!start.unread||input.unreadOnly)return{items,nextCursor:null,unreadCount:first.unreadCount};let remaining=input.limit-items.length;if(remaining<=0)return{items,nextCursor:encodeInboxCursor({unread:!1}),unreadCount:first.unreadCount};let rest=await fimo.execute("notifications.list",{projectId,...query,unread:!1,limit:remaining});return{items:[...items,...rest.items.map(toListItem)],nextCursor:rest.nextCursor?encodeInboxCursor({unread:!1,after:rest.nextCursor}):null,unreadCount:first.unreadCount}}__name(fetchInboxPage,"fetchInboxPage");function buildInboxListHint(nextCursor,limit,options){let trailingArgs=[];return options.topic&&trailingArgs.push("--topic",options.topic),options.unread&&trailingArgs.push("--unread"),options.archived&&trailingArgs.push("--archived"),options.project&&trailingArgs.push("--project",options.project),options.cwd&&trailingArgs.push("--cwd",options.cwd),buildPaginationHint(["fimo","inbox","list"],{cursor:nextCursor,limit,trailingArgs})}__name(buildInboxListHint,"buildInboxListHint");function toListItem(view){let{notification,recipient}=view,payload=notification.payload,summary2="summary"in payload?payload.summary??null:null;return{id:notification.id,topic:payload.topic,title:"title"in payload&&payload.title?payload.title:fallbackTitle(view),description:payload.topic==="agent_question"?payload.description:summary2,from:actorName(notification.actor),receivedAt:isoTimestamp(notification.createdAt),read:!!recipient.readAt,archived:!!recipient.archivedAt}}__name(toListItem,"toListItem");function toQuestionView(question){return{state:question.state,agent:agentDisplayName(question.agentKey),askedAt:isoTimestamp(question.askedAt),expiresAt:isoTimestamp(question.expiresAt),description:question.request.description,form:question.request.block,answer:question.answer?answeredSteps(question):null,capabilities:capabilityDecision(question)}}__name(toQuestionView,"toQuestionView");function answeredSteps(question){return(question.answer?.answer.questions??[]).map(item=>({stepId:item.stepId??null,header:item.header,question:item.question,answer:item.answer,selected:item.selectedLabels,note:item.freeText}))}__name(answeredSteps,"answeredSteps");function capabilityDecision(question){let decision=agentQuestionCapabilityDecision(question.request,question.answer);return decision.requested.length===0?null:{approved:decision.approved,denied:decision.denied}}__name(capabilityDecision,"capabilityDecision");function agentDisplayName(agentKey){return/^project-agent:[^:]+:(.+)$/.exec(agentKey)?.[1]??agentKey}__name(agentDisplayName,"agentDisplayName");function actorName(actor){switch(actor.kind){case"agent":return agentDisplayName(actor.agentKey);case"user":return"A teammate";case"system":return"Fimo"}}__name(actorName,"actorName");function fallbackTitle(view){let who=actorName(view.notification.actor);switch(view.subject.kind){case"question":return`${who} is waiting on an answer`;case"run_outcome":return`${who} ${view.subject.outcome==="completed"?"finished a run":`${view.subject.outcome} a run`}`;case"retained_review":return`${who} left work for review`;case"merge_conflict":return`${who} hit a merge conflict`}}__name(fallbackTitle,"fallbackTitle");function topicLabel(topic){switch(topic){case"agent_question":return"Question";case"agent_run_outcome":return"Run outcome";case"agent_retained_review":return"Work for review";case"agent_conflict":return"Merge conflict"}}__name(topicLabel,"topicLabel");function isoTimestamp(value){let date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?String(value):date.toISOString()}__name(isoTimestamp,"isoTimestamp");function formatTimestamp2(value){return value.length>=16?value.slice(0,16).replace("T"," "):value}__name(formatTimestamp2,"formatTimestamp");function renderInboxList(result){let lines=[`Inbox \xB7 ${result.unreadCount} unread`,""];if(result.items.length===0)return lines.push("Nothing here."),lines.join(`
|
|
707
|
+
`);addScopeOptions3(addPaginationOptions(inbox.command("list").description("List notifications, unread first").option("--topic <topic>",`Only one topic (${WORK_NOTIFICATION_TOPICS.join(", ")})`).option("--unread","Only unread notifications").option("--archived","Only archived notifications"),{defaultLimit:20,maxLimit:100})).action((options,command)=>inboxListCommand(options,command)),addScopeOptions3(inbox.command("get <notificationId>").description("Show one notification, with the stored form when it is a question")).action((notificationId,options,command)=>inboxGetCommand(notificationId,options,command)),addScopeOptions3(inbox.command("answer <notificationId>").description("Answer the question a notification points at, continuing the run that asked").option("--body <json>",'Compact answer JSON: {"answers":[{"stepId":"\u2026","selected":[\u2026],"note":"\u2026"}]}').option("--file <path>","Read the compact answer JSON from a file").option("--stdin","Read the compact answer JSON from stdin")).action((notificationId,options,command)=>inboxAnswerCommand(notificationId,options,command))}__name(registerInboxCommands,"registerInboxCommands");function addScopeOptions3(command){return command.option("--project <id>","Project id (defaults to the linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions3,"addScopeOptions");async function inboxListCommand(options,command){await runInboxCommand("inbox list",async()=>{let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100}),topic=parseTopic(options.topic),{fimo,projectId}=await resolveInboxScope(options,command),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(cursor=>fetchInboxPage(fimo,projectId,{cursor,limit:pagination.limit,topic,unreadOnly:options.unread===!0,archived:options.archived===!0}),"fetchPage")}),result={items:page.items,nextCursor:page.nextCursor,unreadCount:page.unreadCount},hint=page.nextCursor?buildInboxListHint(page.nextCursor,pagination.limit,options):void 0;ui.result({command:"inbox list",data:result,render:__name(()=>renderInboxList(result),"render"),...hint?{hint}:{}})})}__name(inboxListCommand,"inboxListCommand");async function inboxGetCommand(notificationId,options,command){await runInboxCommand("inbox get",async()=>{let{fimo,projectId}=await resolveInboxScope(options,command),view=await fimo.execute("notifications.get",{projectId,notificationId}),question=view.subject.kind==="question"?await fimo.execute("questions.get",{projectId,questionId:view.subject.questionId}):null,result={notification:toListItem(view),question:question?toQuestionView(question):null};ui.result({command:"inbox get",data:result,render:__name(()=>renderInboxItem(result,notificationId),"render")})})}__name(inboxGetCommand,"inboxGetCommand");async function inboxAnswerCommand(notificationId,options,command){await runInboxCommand("inbox answer",async()=>{let compact=parseCompactAnswer(await readContentInputSource(options,message=>new InboxAnswerError(message))),{fimo,projectId}=await resolveInboxScope(options,command),view=await fimo.execute("notifications.get",{projectId,notificationId});if(view.subject.kind!=="question")throw new InboxCommandError("INBOX_NOT_A_QUESTION",`This notification is a ${topicLabel(view.notification.payload.topic).toLowerCase()}, not a question, so there is nothing to answer.`,"Run `fimo inbox list --topic agent_question` to find the questions waiting on an answer.");let question=await fimo.execute("questions.get",{projectId,questionId:view.subject.questionId});if(question.state!=="open")throw new InboxCommandError("INBOX_QUESTION_CLOSED",`This question is ${question.state} and cannot be answered again.`,"Run `fimo inbox get <notification-id>` to read the answer already on record.");let answer=buildQuestionAnswer(question.request.block,compact),submitted=await fimo.execute("questions.answer",{projectId,questionId:view.subject.questionId,answer}),result={notification:toListItem(view),state:submitted.question.state,answer:answeredSteps(submitted.question),capabilities:capabilityDecision(submitted.question),replay:submitted.deduped};ui.result({command:"inbox answer",data:result,render:__name(()=>renderInboxAnswer(result),"render")})})}__name(inboxAnswerCommand,"inboxAnswerCommand");var API_ERROR_CODES={notification_not_found:"INBOX_NOT_FOUND",question_not_found:"INBOX_NOT_FOUND",question_not_open:"INBOX_QUESTION_CLOSED",question_answer_mismatch:"INBOX_ANSWER_INVALID",invalid_notification_cursor:"INBOX_INVALID_CURSOR"};async function runInboxCommand(command,operation){try{await operation()}catch(error){if(error instanceof InboxCommandError||error instanceof InboxAnswerError){ui.error({command,code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}});return}if(error instanceof ApiRequestError){ui.error({command,code:API_ERROR_CODES[error.code??""]??"INBOX_REQUEST_FAILED",message:error.detail});return}throw error}}__name(runInboxCommand,"runInboxCommand");async function resolveInboxScope(options,command){let fimo=createCliFimoClient(loadConfig());if(options.project)return{fimo,projectId:options.project};let ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverrideFromCommand(command)});return{fimo,projectId:ctx.projectId}}__name(resolveInboxScope,"resolveInboxScope");function parseTopic(value){if(value!==void 0){if(!WORK_NOTIFICATION_TOPICS.includes(value))throw new InboxCommandError("INBOX_UNKNOWN_TOPIC",`'${value}' is not an Inbox topic.`,`Topics: ${WORK_NOTIFICATION_TOPICS.join(", ")}.`);return value}}__name(parseTopic,"parseTopic");function encodeInboxCursor(cursor){return Buffer.from(JSON.stringify(cursor)).toString("base64url")}__name(encodeInboxCursor,"encodeInboxCursor");function decodeInboxCursor(raw){if(raw===void 0)return{unread:!0};try{let parsed=JSON.parse(Buffer.from(raw,"base64url").toString());if(typeof parsed.unread!="boolean"||parsed.after!==void 0&&typeof parsed.after!="string")throw new Error("unreadable cursor");return{unread:parsed.unread,...parsed.after!==void 0?{after:parsed.after}:{}}}catch{throw new InboxCommandError("INBOX_INVALID_CURSOR","The list cursor is not readable.","Pass the `nextCursor` from the previous page, or start over without --cursor.")}}__name(decodeInboxCursor,"decodeInboxCursor");async function fetchInboxPage(fimo,projectId,input){let query={...input.topic?{topic:input.topic}:{},...input.archived?{archived:!0}:{}},start=decodeInboxCursor(input.cursor),first=await fimo.execute("notifications.list",{projectId,...query,unread:start.unread,limit:input.limit,...start.after!==void 0?{cursor:start.after}:{}}),items=first.items.map(toListItem);if(first.nextCursor)return{items,nextCursor:encodeInboxCursor({unread:start.unread,after:first.nextCursor}),unreadCount:first.unreadCount};if(!start.unread||input.unreadOnly)return{items,nextCursor:null,unreadCount:first.unreadCount};let remaining=input.limit-items.length;if(remaining<=0)return{items,nextCursor:encodeInboxCursor({unread:!1}),unreadCount:first.unreadCount};let rest=await fimo.execute("notifications.list",{projectId,...query,unread:!1,limit:remaining});return{items:[...items,...rest.items.map(toListItem)],nextCursor:rest.nextCursor?encodeInboxCursor({unread:!1,after:rest.nextCursor}):null,unreadCount:first.unreadCount}}__name(fetchInboxPage,"fetchInboxPage");function buildInboxListHint(nextCursor,limit,options){let trailingArgs=[];return options.topic&&trailingArgs.push("--topic",options.topic),options.unread&&trailingArgs.push("--unread"),options.archived&&trailingArgs.push("--archived"),options.project&&trailingArgs.push("--project",options.project),options.cwd&&trailingArgs.push("--cwd",options.cwd),buildPaginationHint(["fimo","inbox","list"],{cursor:nextCursor,limit,trailingArgs})}__name(buildInboxListHint,"buildInboxListHint");function toListItem(view){let{notification,recipient}=view,payload=notification.payload,summary2="summary"in payload?payload.summary??null:null;return{id:notification.id,topic:payload.topic,title:"title"in payload&&payload.title?payload.title:fallbackTitle(view),description:payload.topic==="agent_question"?payload.description:payload.topic==="publication_failed"?`Changes from ${payload.sourceBranch} were not published.`:summary2,from:actorName(notification.actor),receivedAt:isoTimestamp(notification.createdAt),read:!!recipient.readAt,archived:!!recipient.archivedAt}}__name(toListItem,"toListItem");function toQuestionView(question){return{state:question.state,agent:agentDisplayName(question.agentKey),askedAt:isoTimestamp(question.askedAt),expiresAt:isoTimestamp(question.expiresAt),description:question.request.description,form:question.request.block,answer:question.answer?answeredSteps(question):null,capabilities:capabilityDecision(question)}}__name(toQuestionView,"toQuestionView");function answeredSteps(question){return(question.answer?.answer.questions??[]).map(item=>({stepId:item.stepId??null,header:item.header,question:item.question,answer:item.answer,selected:item.selectedLabels,note:item.freeText}))}__name(answeredSteps,"answeredSteps");function capabilityDecision(question){let decision=agentQuestionCapabilityDecision(question.request,question.answer);return decision.requested.length===0?null:{approved:decision.approved,denied:decision.denied}}__name(capabilityDecision,"capabilityDecision");function agentDisplayName(agentKey){return/^project-agent:[^:]+:(.+)$/.exec(agentKey)?.[1]??agentKey}__name(agentDisplayName,"agentDisplayName");function actorName(actor){switch(actor.kind){case"agent":return agentDisplayName(actor.agentKey);case"user":return"A teammate";case"system":return"Fimo"}}__name(actorName,"actorName");function fallbackTitle(view){let who=actorName(view.notification.actor);switch(view.subject.kind){case"question":return`${who} is waiting on an answer`;case"run_outcome":return`${who} ${view.subject.outcome==="completed"?"finished a run":`${view.subject.outcome} a run`}`;case"retained_review":return`${who} left work for review`;case"merge_conflict":return`${who} hit a merge conflict`;case"publication":{let payload=view.notification.payload;return payload.topic==="publication_failed"&&payload.firstPublication?"Your website hasn't been published yet":"Your latest update couldn't be published"}}}__name(fallbackTitle,"fallbackTitle");function topicLabel(topic){switch(topic){case"agent_question":return"Question";case"agent_run_outcome":return"Run outcome";case"agent_retained_review":return"Work for review";case"agent_conflict":return"Merge conflict";case"publication_failed":return"Publication failure"}}__name(topicLabel,"topicLabel");function isoTimestamp(value){let date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?String(value):date.toISOString()}__name(isoTimestamp,"isoTimestamp");function formatTimestamp2(value){return value.length>=16?value.slice(0,16).replace("T"," "):value}__name(formatTimestamp2,"formatTimestamp");function renderInboxList(result){let lines=[`Inbox \xB7 ${result.unreadCount} unread`,""];if(result.items.length===0)return lines.push("Nothing here."),lines.join(`
|
|
708
708
|
`);for(let item of result.items)lines.push(`${item.read?" ":"*"} ${item.title}`,` ${topicLabel(item.topic)} \xB7 ${item.from} \xB7 ${formatTimestamp2(item.receivedAt)}${item.archived?" \xB7 archived":""}`),item.description&&lines.push(` ${item.description}`),lines.push(` fimo inbox get ${item.id}`,"");return lines.join(`
|
|
709
709
|
`).trimEnd()}__name(renderInboxList,"renderInboxList");function renderInboxItem(result,notificationId){let{notification,question}=result,lines=[notification.title,`${topicLabel(notification.topic)} \xB7 ${notification.from} \xB7 ${formatTimestamp2(notification.receivedAt)}${notification.read?"":" \xB7 unread"}${notification.archived?" \xB7 archived":""}`];if(notification.description&&lines.push("",notification.description),!question)return lines.join(`
|
|
710
710
|
`);if(lines.push("",`Question \xB7 ${question.state} \xB7 asked ${formatTimestamp2(question.askedAt)} \xB7 expires ${formatTimestamp2(question.expiresAt)}`,"",question.description),question.form.steps.forEach((step,index)=>{lines.push("",`Step ${index+1} \xB7 ${step.id} \xB7 ${step.header}`,` ${step.question}`),lines.push(...renderStepBody(step).map(line=>` ${line}`))}),question.answer){lines.push("","Answered:");for(let item of question.answer)lines.push(` ${item.header}: ${item.answer.replaceAll(`
|
|
@@ -714,7 +714,7 @@ Examples:
|
|
|
714
714
|
`," ")}`);return result.capabilities&&lines.push(`Capabilities approved: ${result.capabilities.approved.join(", ")||"none"}`,`Capabilities denied: ${result.capabilities.denied.join(", ")||"none"}`),lines.join(`
|
|
715
715
|
`)}__name(renderInboxAnswer,"renderInboxAnswer");import fs36 from"node:fs";import path37 from"node:path";init_dist();init_auth();init_config();init_sdk_transport();import fs34 from"node:fs";import os2 from"node:os";import path34 from"node:path";var isPlainObject=__name(value=>value!==null&&typeof value=="object"&&!Array.isArray(value),"isPlainObject"),toErrorMessage=__name((error,fallback="Unknown error")=>error instanceof Error?error.message:fallback,"toErrorMessage");var import_yaml4=__toESM(require_dist3(),1);import{existsSync as existsSync9}from"node:fs";import{homedir as homedir2,platform as platform2,tmpdir as tmpdir2}from"node:os";import{basename as basename3,dirname as dirname6,isAbsolute as isAbsolute3,join as join10,normalize,relative as relative2,resolve as resolve8,sep}from"node:path";import{cp,lstat,mkdir,mkdtemp,readFile as readFile4,readdir,readlink,realpath,rm,stat,symlink,writeFile}from"node:fs/promises";import{spawn as spawn2}from"node:child_process";var xdgConfigHome=__name(()=>{let explicit=process.env.XDG_CONFIG_HOME?.trim();if(explicit)return explicit;if(platform2()==="win32"){let localAppData=process.env.LOCALAPPDATA?.trim();if(localAppData)return localAppData}return join10(homedir2(),".config")},"xdgConfigHome"),CANONICAL_SKILLS_DIR=".agents/skills",SKILL_MANIFEST_FILE="SKILL.md",DEFAULT_CLONE_TIMEOUT_MS=3e5,DEFAULT_FETCH_TIMEOUT_MS=3e4,MS_PER_SECOND=1e3,SKIP_DISCOVERY_DIRS=new Set(["node_modules",".git","dist","build","__pycache__","coverage",".next",".turbo"]),COPY_EXCLUDE_FILES=new Set(["metadata.json"]),COPY_EXCLUDE_DIRS=new Set([".git","__pycache__","__pypackages__"]),WELL_KNOWN_INDEX_FILE="index.json",WELL_KNOWN_PATHS=[".well-known/agent-skills",".well-known/skills"],home=homedir2(),configHome=xdgConfigHome(),codexHome=process.env.CODEX_HOME?.trim()||join10(home,".codex"),claudeHome=process.env.CLAUDE_CONFIG_DIR?.trim()||join10(home,".claude"),vibeHome=process.env.VIBE_HOME?.trim()||join10(home,".vibe"),resolveOpenClawGlobalSkillsDir=__name(()=>existsSync9(join10(home,".openclaw"))?join10(home,".openclaw/skills"):existsSync9(join10(home,".clawdbot"))?join10(home,".clawdbot/skills"):existsSync9(join10(home,".moltbot"))?join10(home,".moltbot/skills"):join10(home,".openclaw/skills"),"resolveOpenClawGlobalSkillsDir"),detectOpenClaw=__name(()=>existsSync9(join10(home,".openclaw"))||existsSync9(join10(home,".clawdbot"))||existsSync9(join10(home,".moltbot")),"detectOpenClaw"),skillAgents={adal:{name:"adal",displayName:"AdaL",skillsDir:".adal/skills",globalSkillsDir:join10(home,".adal/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".adal")),"detectInstalled")},"aider-desk":{name:"aider-desk",displayName:"AiderDesk",skillsDir:".aider-desk/skills",globalSkillsDir:join10(home,".aider-desk/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".aider-desk")),"detectInstalled")},amp:{name:"amp",displayName:"Amp",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"amp")),"detectInstalled"),isUniversal:!0},antigravity:{name:"antigravity",displayName:"Antigravity",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".gemini/antigravity/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".gemini/antigravity")),"detectInstalled"),isUniversal:!0},augment:{name:"augment",displayName:"Augment",skillsDir:".augment/skills",globalSkillsDir:join10(home,".augment/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".augment")),"detectInstalled")},bob:{name:"bob",displayName:"IBM Bob",skillsDir:".bob/skills",globalSkillsDir:join10(home,".bob/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".bob")),"detectInstalled")},"claude-code":{name:"claude-code",displayName:"Claude Code",skillsDir:".claude/skills",globalSkillsDir:join10(claudeHome,"skills"),detectInstalled:__name(async()=>existsSync9(claudeHome),"detectInstalled")},cline:{name:"cline",displayName:"Cline",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".cline")),"detectInstalled"),isUniversal:!0},"codearts-agent":{name:"codearts-agent",displayName:"CodeArts Agent",skillsDir:".codeartsdoer/skills",globalSkillsDir:join10(home,".codeartsdoer/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codeartsdoer")),"detectInstalled")},codebuddy:{name:"codebuddy",displayName:"CodeBuddy",skillsDir:".codebuddy/skills",globalSkillsDir:join10(home,".codebuddy/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".codebuddy"))||existsSync9(join10(home,".codebuddy")),"detectInstalled")},codemaker:{name:"codemaker",displayName:"Codemaker",skillsDir:".codemaker/skills",globalSkillsDir:join10(home,".codemaker/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codemaker")),"detectInstalled")},codestudio:{name:"codestudio",displayName:"Code Studio",skillsDir:".codestudio/skills",globalSkillsDir:join10(home,".codestudio/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codestudio")),"detectInstalled")},codex:{name:"codex",displayName:"Codex",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(codexHome,"skills"),detectInstalled:__name(async()=>existsSync9(codexHome)||existsSync9("/etc/codex"),"detectInstalled"),isUniversal:!0},"command-code":{name:"command-code",displayName:"Command Code",skillsDir:".commandcode/skills",globalSkillsDir:join10(home,".commandcode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".commandcode")),"detectInstalled")},continue:{name:"continue",displayName:"Continue",skillsDir:".continue/skills",globalSkillsDir:join10(home,".continue/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".continue"))||existsSync9(join10(home,".continue")),"detectInstalled")},cortex:{name:"cortex",displayName:"Cortex Code",skillsDir:".cortex/skills",globalSkillsDir:join10(home,".snowflake/cortex/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".snowflake/cortex")),"detectInstalled")},crush:{name:"crush",displayName:"Crush",skillsDir:".crush/skills",globalSkillsDir:join10(configHome,"crush/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"crush")),"detectInstalled")},cursor:{name:"cursor",displayName:"Cursor",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".cursor/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".cursor")),"detectInstalled"),isUniversal:!0},deepagents:{name:"deepagents",displayName:"Deep Agents",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".deepagents/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".deepagents")),"detectInstalled"),isUniversal:!0},devin:{name:"devin",displayName:"Devin",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"devin/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"devin")),"detectInstalled"),isUniversal:!0},dexto:{name:"dexto",displayName:"Dexto",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".dexto")),"detectInstalled"),isUniversal:!0},droid:{name:"droid",displayName:"Factory Droid",skillsDir:".factory/skills",globalSkillsDir:join10(home,".factory/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".factory")),"detectInstalled")},firebender:{name:"firebender",displayName:"Firebender",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".firebender/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".firebender")),"detectInstalled"),isUniversal:!0},forgecode:{name:"forgecode",displayName:"ForgeCode",skillsDir:".forge/skills",globalSkillsDir:join10(home,".forge/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".forge")),"detectInstalled")},"gemini-cli":{name:"gemini-cli",displayName:"Gemini CLI",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".gemini/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".gemini")),"detectInstalled"),isUniversal:!0},"github-copilot":{name:"github-copilot",displayName:"GitHub Copilot",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".copilot/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".copilot")),"detectInstalled"),isUniversal:!0},goose:{name:"goose",displayName:"Goose",skillsDir:".goose/skills",globalSkillsDir:join10(configHome,"goose/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"goose")),"detectInstalled")},"iflow-cli":{name:"iflow-cli",displayName:"iFlow CLI",skillsDir:".iflow/skills",globalSkillsDir:join10(home,".iflow/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".iflow")),"detectInstalled")},junie:{name:"junie",displayName:"Junie",skillsDir:".junie/skills",globalSkillsDir:join10(home,".junie/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".junie")),"detectInstalled")},kilo:{name:"kilo",displayName:"Kilo Code",skillsDir:".kilocode/skills",globalSkillsDir:join10(home,".kilocode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kilocode")),"detectInstalled")},"kimi-cli":{name:"kimi-cli",displayName:"Kimi Code CLI",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kimi")),"detectInstalled"),isUniversal:!0},"kiro-cli":{name:"kiro-cli",displayName:"Kiro CLI",skillsDir:".kiro/skills",globalSkillsDir:join10(home,".kiro/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kiro")),"detectInstalled")},kode:{name:"kode",displayName:"Kode",skillsDir:".kode/skills",globalSkillsDir:join10(home,".kode/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".kode")),"detectInstalled")},mcpjam:{name:"mcpjam",displayName:"MCPJam",skillsDir:".mcpjam/skills",globalSkillsDir:join10(home,".mcpjam/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".mcpjam")),"detectInstalled")},"mistral-vibe":{name:"mistral-vibe",displayName:"Mistral Vibe",skillsDir:".vibe/skills",globalSkillsDir:join10(vibeHome,"skills"),detectInstalled:__name(async()=>existsSync9(vibeHome),"detectInstalled")},mux:{name:"mux",displayName:"Mux",skillsDir:".mux/skills",globalSkillsDir:join10(home,".mux/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".mux")),"detectInstalled")},neovate:{name:"neovate",displayName:"Neovate",skillsDir:".neovate/skills",globalSkillsDir:join10(home,".neovate/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".neovate")),"detectInstalled")},openclaw:{name:"openclaw",displayName:"OpenClaw",skillsDir:"skills",globalSkillsDir:resolveOpenClawGlobalSkillsDir(),detectInstalled:__name(async()=>detectOpenClaw(),"detectInstalled")},opencode:{name:"opencode",displayName:"OpenCode",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"opencode/skills"),detectInstalled:__name(async()=>existsSync9(join10(configHome,"opencode")),"detectInstalled"),isUniversal:!0},openhands:{name:"openhands",displayName:"OpenHands",skillsDir:".openhands/skills",globalSkillsDir:join10(home,".openhands/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".openhands")),"detectInstalled")},pi:{name:"pi",displayName:"Pi",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".pi/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".pi")),"detectInstalled"),isUniversal:!0},pochi:{name:"pochi",displayName:"Pochi",skillsDir:".pochi/skills",globalSkillsDir:join10(home,".pochi/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".pochi")),"detectInstalled")},qoder:{name:"qoder",displayName:"Qoder",skillsDir:".qoder/skills",globalSkillsDir:join10(home,".qoder/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".qoder")),"detectInstalled")},"qwen-code":{name:"qwen-code",displayName:"Qwen Code",skillsDir:".qwen/skills",globalSkillsDir:join10(home,".qwen/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".qwen")),"detectInstalled")},replit:{name:"replit",displayName:"Replit",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(configHome,"agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(process.cwd(),".replit")),"detectInstalled"),isUniversal:!0},roo:{name:"roo",displayName:"Roo Code",skillsDir:".roo/skills",globalSkillsDir:join10(home,".roo/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".roo")),"detectInstalled")},rovodev:{name:"rovodev",displayName:"Rovo Dev",skillsDir:".rovodev/skills",globalSkillsDir:join10(home,".rovodev/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".rovodev")),"detectInstalled")},"tabnine-cli":{name:"tabnine-cli",displayName:"Tabnine CLI",skillsDir:".tabnine/agent/skills",globalSkillsDir:join10(home,".tabnine/agent/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".tabnine")),"detectInstalled")},trae:{name:"trae",displayName:"Trae",skillsDir:".trae/skills",globalSkillsDir:join10(home,".trae/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".trae")),"detectInstalled")},"trae-cn":{name:"trae-cn",displayName:"Trae CN",skillsDir:".trae/skills",globalSkillsDir:join10(home,".trae-cn/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".trae-cn")),"detectInstalled")},universal:{name:"universal",displayName:"Universal",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>!1,"detectInstalled"),isUniversal:!0},warp:{name:"warp",displayName:"Warp",skillsDir:CANONICAL_SKILLS_DIR,globalSkillsDir:join10(home,".agents/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".warp")),"detectInstalled"),isUniversal:!0},windsurf:{name:"windsurf",displayName:"Windsurf",skillsDir:".windsurf/skills",globalSkillsDir:join10(home,".codeium/windsurf/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".codeium/windsurf")),"detectInstalled")},zencoder:{name:"zencoder",displayName:"Zencoder",skillsDir:".zencoder/skills",globalSkillsDir:join10(home,".zencoder/skills"),detectInstalled:__name(async()=>existsSync9(join10(home,".zencoder")),"detectInstalled")}},getSkillAgentConfig=__name(agentType=>skillAgents[agentType],"getSkillAgentConfig"),isUniversalSkillAgent=__name(agentType=>!!skillAgents[agentType].isUniversal,"isUniversalSkillAgent"),getSkillAgentDir=__name((agentType,options={})=>{let agent=skillAgents[agentType];return options.global??!1?agent.globalSkillsDir??join10(home,agent.skillsDir):join10(options.cwd??process.cwd(),agent.skillsDir)},"getSkillAgentDir"),agentConfigEntries=__name(()=>Object.values(skillAgents).map(config=>[config.name,config]),"agentConfigEntries"),getSkillAgentTypes=__name(()=>agentConfigEntries().map(([name])=>name),"getSkillAgentTypes"),isSkillAgentType=__name(value=>value in skillAgents,"isSkillAgentType"),getUniversalSkillAgents=__name(()=>agentConfigEntries().filter(([name,config])=>config.isUniversal&&name!=="universal").map(([name])=>name),"getUniversalSkillAgents");var detectInstalledSkillAgents=__name(async()=>(await Promise.all(Object.values(skillAgents).map(async config=>({name:config.name,installed:await config.detectInstalled()})))).filter(entry=>entry.installed).map(entry=>entry.name),"detectInstalledSkillAgents"),parseFrontmatter=__name(raw=>{let match=raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!match)return{data:{},content:raw};let parsed=(0,import_yaml4.parse)(match[1]??"");return{data:isPlainObject(parsed)?parsed:{},content:match[2]??""}},"parseFrontmatter"),sanitizeName=__name(name=>name.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill","sanitizeName"),fetchSkillManifestFromUrl=__name(async url=>{let controller=new AbortController,timer=setTimeout(()=>controller.abort(),DEFAULT_FETCH_TIMEOUT_MS);try{let response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error(`Failed to fetch ${url}: HTTP ${response.status}`);let content2=await response.text(),{data}=parseFrontmatter(content2);if(typeof data.name!="string"||!data.name)throw new Error(`Fetched SKILL.md has no "name" in its frontmatter: ${url}`);let skillName=sanitizeName(data.name),baseDir=await mkdtemp(join10(tmpdir2(),"agent-install-url-")),skillDir=join10(baseDir,skillName);return await mkdir(dirname6(join10(skillDir,SKILL_MANIFEST_FILE)),{recursive:!0}),await writeFile(join10(skillDir,SKILL_MANIFEST_FILE),content2,"utf-8"),baseDir}finally{clearTimeout(timer)}},"fetchSkillManifestFromUrl"),isPathSafe=__name((basePath,targetPath)=>{let normalizedBase=normalize(resolve8(basePath)),normalizedTarget=normalize(resolve8(targetPath));return normalizedTarget.startsWith(normalizedBase+sep)||normalizedTarget===normalizedBase},"isPathSafe"),stripTrailingSlash=__name(input=>input.endsWith("/")?input.slice(0,-1):input,"stripTrailingSlash"),TEMP_PREFIX="agent-install-well-known-",SKILL_NAME_PATTERN=/^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/,WellKnownTimeoutError=class extends Error{static{__name(this,"WellKnownTimeoutError")}constructor(message){super(message),this.name="WellKnownTimeoutError"}},isValidWellKnownEntry=__name(value=>{if(!isPlainObject(value)||typeof value.name!="string"||!value.name||typeof value.description!="string"||!value.description||!Array.isArray(value.files)||value.files.length===0||value.name.length>1&&!SKILL_NAME_PATTERN.test(value.name)||value.name.length===1&&!/^[a-z0-9]$/.test(value.name))return!1;for(let file of value.files)if(typeof file!="string"||file.startsWith("/")||file.startsWith("\\")||file.includes(".."))return!1;return value.files.some(file=>typeof file=="string"&&file.toLowerCase()==="skill.md")},"isValidWellKnownEntry"),fetchOk=__name(async url=>{try{let response=await fetch(url,{signal:AbortSignal.timeout(DEFAULT_FETCH_TIMEOUT_MS)});return response.ok?response:null}catch(error){if(error instanceof DOMException&&error.name==="TimeoutError")throw new WellKnownTimeoutError(`Request timed out: ${url}`);return null}},"fetchOk"),buildIndexCandidates=__name(inputUrl=>{let parsed=new URL(inputUrl),basePath=stripTrailingSlash(parsed.pathname),candidates=[];for(let wellKnownPath of WELL_KNOWN_PATHS)candidates.push({indexUrl:`${parsed.protocol}//${parsed.host}${basePath}/${wellKnownPath}/${WELL_KNOWN_INDEX_FILE}`,baseUrl:`${parsed.protocol}//${parsed.host}${basePath}`,wellKnownPath}),basePath&&candidates.push({indexUrl:`${parsed.protocol}//${parsed.host}/${wellKnownPath}/${WELL_KNOWN_INDEX_FILE}`,baseUrl:`${parsed.protocol}//${parsed.host}`,wellKnownPath});return candidates},"buildIndexCandidates"),extractRequestedSkillName=__name(inputUrl=>{try{let name=new URL(inputUrl).pathname.match(/\/.well-known\/(?:agent-skills|skills)\/([^/]+)\/?$/)?.[1];return name&&name!=="index.json"?name:void 0}catch{return}},"extractRequestedSkillName"),validateIndexEntries=__name(payload=>{if(!isPlainObject(payload))return null;let{skills:skills2}=payload;return!Array.isArray(skills2)||!skills2.every(isValidWellKnownEntry)?null:skills2},"validateIndexEntries"),resolveIndex=__name(async inputUrl=>{for(let candidate of buildIndexCandidates(inputUrl)){let response=await fetchOk(candidate.indexUrl);if(!response)continue;let payload;try{payload=await response.json()}catch{continue}let entries2=validateIndexEntries(payload);if(entries2)return{entries:entries2,baseUrl:candidate.baseUrl,wellKnownPath:candidate.wellKnownPath,requestedSkillName:extractRequestedSkillName(inputUrl)}}return null},"resolveIndex"),writeSkillFiles=__name(async(resolved,entry,rootDir)=>{let skillDir=join10(rootDir,sanitizeName(entry.name));await mkdir(skillDir,{recursive:!0});let skillBaseUrl=`${stripTrailingSlash(resolved.baseUrl)}/${resolved.wellKnownPath}/${entry.name}`,installedAny=!1;return await Promise.all(entry.files.map(async relativePath=>{let targetPath=join10(skillDir,relativePath);if(!isPathSafe(skillDir,targetPath))return;let response=await fetchOk(`${skillBaseUrl}/${relativePath}`);if(!response)return;let content2=await response.text();await mkdir(dirname6(targetPath),{recursive:!0}),await writeFile(targetPath,content2,"utf-8"),installedAny=!0})),installedAny},"writeSkillFiles"),fetchWellKnownSkills=__name(async inputUrl=>{let resolved=await resolveIndex(inputUrl).catch(error=>{throw error instanceof WellKnownTimeoutError?new Error(`Timed out resolving well-known skills index at ${inputUrl}. Set the source's HTTP server to respond faster, or pass a local path.`):error});if(!resolved)throw new Error(`No /.well-known/agent-skills/index.json (or fallback /.well-known/skills/index.json) found at ${inputUrl}`);let entries2=resolved.requestedSkillName?resolved.entries.filter(entry=>entry.name===resolved.requestedSkillName):resolved.entries;if(entries2.length===0)throw new Error(resolved.requestedSkillName?`Skill "${resolved.requestedSkillName}" not found in well-known index at ${inputUrl}`:`Well-known index at ${inputUrl} declares no skills`);let baseDir=await mkdtemp(join10(tmpdir2(),TEMP_PREFIX));if(!(await Promise.all(entries2.map(entry=>writeSkillFiles(resolved,entry,baseDir)))).some(Boolean))throw new Error(`Failed to fetch any skill files from well-known index at ${inputUrl}`);return baseDir},"fetchWellKnownSkills"),readJsonObjectIfExists=__name(async path52=>{try{let content2=await readFile4(path52,"utf-8"),parsed=JSON.parse(content2);return isPlainObject(parsed)?parsed:null}catch{return null}},"readJsonObjectIfExists"),MARKETPLACE_RELATIVE_PATH=".claude-plugin/marketplace.json",PLUGIN_RELATIVE_PATH=".claude-plugin/plugin.json",PLUGIN_SKILLS_SUBDIR="skills",isClaudeRelativePath=__name(input=>typeof input=="string"&&input.startsWith("./"),"isClaudeRelativePath"),stringValueOrEmpty=__name(input=>typeof input=="string"?input:"","stringValueOrEmpty"),resolvePluginRoot=__name(manifest=>{if(!isPlainObject(manifest.metadata))return"";let rawPluginRoot=manifest.metadata.pluginRoot;return rawPluginRoot===void 0?"":isClaudeRelativePath(rawPluginRoot)?rawPluginRoot:null},"resolvePluginRoot"),collectPluginSkillSearchDirs=__name((basePath,pluginBase,rawSkills,searchDirs)=>{if(isPathSafe(basePath,pluginBase)){if(Array.isArray(rawSkills))for(let entry of rawSkills){if(!isClaudeRelativePath(entry))continue;let skillDir=dirname6(join10(pluginBase,entry));isPathSafe(basePath,skillDir)&&searchDirs.push(skillDir)}searchDirs.push(join10(pluginBase,PLUGIN_SKILLS_SUBDIR))}},"collectPluginSkillSearchDirs"),collectPluginGroupings=__name((basePath,pluginBase,pluginName,rawSkills,groupings)=>{if(!(!isPathSafe(basePath,pluginBase)||!Array.isArray(rawSkills)))for(let entry of rawSkills){if(!isClaudeRelativePath(entry))continue;let skillDir=join10(pluginBase,entry);isPathSafe(basePath,skillDir)&&groupings.set(resolve8(skillDir),pluginName)}},"collectPluginGroupings"),getPluginSkillPaths=__name(async basePath=>{let searchDirs=[],marketplace=await readJsonObjectIfExists(join10(basePath,MARKETPLACE_RELATIVE_PATH));if(marketplace){let pluginRoot=resolvePluginRoot(marketplace);if(pluginRoot!==null&&Array.isArray(marketplace.plugins))for(let plugin of marketplace.plugins)isPlainObject(plugin)&&(plugin.source!==void 0&&!isClaudeRelativePath(plugin.source)||collectPluginSkillSearchDirs(basePath,join10(basePath,pluginRoot,stringValueOrEmpty(plugin.source)),plugin.skills,searchDirs))}let single=await readJsonObjectIfExists(join10(basePath,PLUGIN_RELATIVE_PATH));return single&&collectPluginSkillSearchDirs(basePath,basePath,single.skills,searchDirs),searchDirs},"getPluginSkillPaths"),getPluginGroupings=__name(async basePath=>{let groupings=new Map,marketplace=await readJsonObjectIfExists(join10(basePath,MARKETPLACE_RELATIVE_PATH));if(marketplace){let pluginRoot=resolvePluginRoot(marketplace);if(pluginRoot!==null&&Array.isArray(marketplace.plugins))for(let plugin of marketplace.plugins)isPlainObject(plugin)&&(typeof plugin.name!="string"||!plugin.name||plugin.source!==void 0&&!isClaudeRelativePath(plugin.source)||collectPluginGroupings(basePath,join10(basePath,pluginRoot,stringValueOrEmpty(plugin.source)),plugin.name,plugin.skills,groupings))}let single=await readJsonObjectIfExists(join10(basePath,PLUGIN_RELATIVE_PATH));return single&&typeof single.name=="string"&&single.name&&collectPluginGroupings(basePath,basePath,single.name,single.skills,groupings),groupings},"getPluginGroupings"),CLONE_TIMEOUT_ENV_VAR="AGENT_INSTALL_CLONE_TIMEOUT_MS",LEGACY_CLONE_TIMEOUT_ENV_VAR="SKILL_INSTALL_CLONE_TIMEOUT_MS",TEMP_CLONE_PREFIX="agent-install-",GitCloneError=class extends Error{static{__name(this,"GitCloneError")}url;kind;constructor(message,url,kind="unknown"){super(message),this.name="GitCloneError",this.url=url,this.kind=kind}get isTimeout(){return this.kind==="timeout"}get isAuthError(){return this.kind==="auth"}},resolveCloneTimeoutMs=__name(()=>{let raw=process.env[CLONE_TIMEOUT_ENV_VAR]??process.env[LEGACY_CLONE_TIMEOUT_ENV_VAR];if(!raw)return DEFAULT_CLONE_TIMEOUT_MS;let parsed=Number.parseInt(raw,10);return Number.isFinite(parsed)&&parsed>0?parsed:DEFAULT_CLONE_TIMEOUT_MS},"resolveCloneTimeoutMs"),runGit2=__name((args,timeoutMs)=>new Promise(resolvePromise=>{let child=spawn2("git",args,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_LFS_SKIP_SMUDGE:"1"}}),stderr="",timedOut=!1,timer=setTimeout(()=>{timedOut=!0,child.kill("SIGKILL")},timeoutMs);child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.on("close",code2=>{clearTimeout(timer),resolvePromise({code:code2??1,stderr,timedOut})}),child.on("error",err=>{clearTimeout(timer),stderr+=err.message,resolvePromise({code:1,stderr,timedOut})})}),"runGit"),AUTH_ERROR_MARKERS=["Authentication failed","could not read Username","Permission denied","Repository not found"],isAuthErrorMessage=__name(stderr=>AUTH_ERROR_MARKERS.some(marker=>stderr.includes(marker)),"isAuthErrorMessage"),cloneRepo2=__name(async(url,ref)=>{let tempDir=await mkdtemp(join10(tmpdir2(),TEMP_CLONE_PREFIX)),timeoutMs=resolveCloneTimeoutMs(),args=["-c","filter.lfs.required=false","-c","filter.lfs.smudge=","-c","filter.lfs.clean=","-c","filter.lfs.process=","clone","--depth","1"];ref&&args.push("--branch",ref),args.push(url,tempDir);let{code:code2,stderr,timedOut}=await runGit2(args,timeoutMs);if(code2===0)return tempDir;throw await rm(tempDir,{recursive:!0,force:!0}).catch(()=>{}),timedOut?new GitCloneError([`Clone timed out after ${Math.round(timeoutMs/MS_PER_SECOND)}s. Common causes:`,` - Large repository: raise the timeout with ${CLONE_TIMEOUT_ENV_VAR}=600000 (10m)`," - Slow network: retry, or clone manually and pass the local path to 'skill add'"," - Private repo without credentials:"," - For SSH: ssh-add -l (to check loaded keys)"," - For HTTPS: gh auth status (if using GitHub CLI)"].join(`
|
|
716
716
|
`),url,"timeout"):isAuthErrorMessage(stderr)?new GitCloneError([`Authentication failed for ${url}.`," - For private repos, ensure you have access"," - For SSH: check your keys with 'ssh -T git@github.com'"," - For HTTPS: run 'gh auth login' or configure git credentials"].join(`
|
|
717
|
-
`),url,"auth"):new GitCloneError(`Failed to clone ${url}: ${stderr.trim()||"unknown error"}`,url)},"cloneRepo"),cleanupTempDir=__name(async dir=>{let normalizedDir=normalize(resolve8(dir)),normalizedTmpDir=normalize(resolve8(tmpdir2()));if(!normalizedDir.startsWith(normalizedTmpDir+sep)&&normalizedDir!==normalizedTmpDir)throw new Error("Attempted to clean up directory outside of temp directory");await rm(dir,{recursive:!0,force:!0})},"cleanupTempDir"),getCanonicalSkillsDir=__name((isGlobal,cwd)=>join10(isGlobal?homedir2():cwd||process.cwd(),CANONICAL_SKILLS_DIR),"getCanonicalSkillsDir"),getSkillAgentBaseDir=__name((agentType,isGlobal,cwd)=>{if(isUniversalSkillAgent(agentType))return getCanonicalSkillsDir(isGlobal,cwd);let agent=getSkillAgentConfig(agentType),baseDir=isGlobal?homedir2():cwd||process.cwd();return isGlobal?agent.globalSkillsDir??join10(baseDir,agent.skillsDir):join10(baseDir,agent.skillsDir)},"getSkillAgentBaseDir"),cleanAndCreateDirectory=__name(async path52=>{await rm(path52,{recursive:!0,force:!0}).catch(()=>{}),await mkdir(path52,{recursive:!0})},"cleanAndCreateDirectory"),resolveSymlinkTarget=__name((linkPath,linkTarget)=>resolve8(dirname6(linkPath),linkTarget),"resolveSymlinkTarget"),resolveParentSymlinks=__name(async path52=>{let resolved=resolve8(path52),parentDir=dirname6(resolved),name=basename3(resolved);try{return join10(await realpath(parentDir),name)}catch{return resolved}},"resolveParentSymlinks"),isPathInsideBase=__name((basePath,targetPath)=>{let normalizedBase=resolve8(basePath),normalizedTarget=resolve8(targetPath);return normalizedTarget===normalizedBase||normalizedTarget.startsWith(normalizedBase+sep)},"isPathInsideBase"),copyDirectory=__name(async(src,dest,rootSrc=src)=>{await mkdir(dest,{recursive:!0});let entries2=await readdir(src,{withFileTypes:!0});await Promise.all(entries2.filter(entry=>!COPY_EXCLUDE_FILES.has(entry.name)&&!(entry.isDirectory()&©_EXCLUDE_DIRS.has(entry.name))).map(async entry=>{let srcPath=join10(src,entry.name),destPath=join10(dest,entry.name);if(entry.isSymbolicLink()){let linkRealPath=await realpath(srcPath).catch(()=>null);if(!linkRealPath||!isPathInsideBase(rootSrc,linkRealPath))return;await cp(srcPath,destPath,{dereference:!0,recursive:!0});return}if(entry.isDirectory()){await copyDirectory(srcPath,destPath,rootSrc);return}await cp(srcPath,destPath,{dereference:!1,recursive:!0})}))},"copyDirectory"),isLoopError=__name(error=>!!(error&&typeof error=="object"&&"code"in error&&error.code==="ELOOP"),"isLoopError"),createSymlink=__name(async(target,linkPath)=>{try{let resolvedTarget=resolve8(target),resolvedLinkPath=resolve8(linkPath),[realTarget,realLinkPath]=await Promise.all([realpath(resolvedTarget).catch(()=>resolvedTarget),realpath(resolvedLinkPath).catch(()=>resolvedLinkPath)]);if(realTarget===realLinkPath)return!0;let[realTargetWithParents,realLinkPathWithParents]=await Promise.all([resolveParentSymlinks(target),resolveParentSymlinks(linkPath)]);if(realTargetWithParents===realLinkPathWithParents)return!0;try{if((await lstat(linkPath)).isSymbolicLink()){if(resolveSymlinkTarget(linkPath,await readlink(linkPath))===resolvedTarget)return!0;await rm(linkPath)}else await rm(linkPath,{recursive:!0})}catch(error){isLoopError(error)&&await rm(linkPath,{force:!0}).catch(()=>{})}let linkDir=dirname6(linkPath);return await mkdir(linkDir,{recursive:!0}),await symlink(relative2(await resolveParentSymlinks(linkDir),target),linkPath,platform2()==="win32"?"junction":void 0),!0}catch{return!1}},"createSymlink"),installByCopy=__name(async(skill,destination)=>(await cleanAndCreateDirectory(destination),await copyDirectory(skill.path,destination),{success:!0,path:destination,mode:"copy"}),"installByCopy"),installBySymlink=__name(async(skill,agentType,canonicalDir,agentDir,isGlobal)=>(await cleanAndCreateDirectory(canonicalDir),await copyDirectory(skill.path,canonicalDir),isGlobal&&isUniversalSkillAgent(agentType)?{success:!0,path:canonicalDir,canonicalPath:canonicalDir,mode:"symlink"}:await createSymlink(canonicalDir,agentDir)?{success:!0,path:agentDir,canonicalPath:canonicalDir,mode:"symlink"}:(await cleanAndCreateDirectory(agentDir),await copyDirectory(skill.path,agentDir),{success:!0,path:agentDir,canonicalPath:canonicalDir,mode:"symlink",symlinkFailed:!0})),"installBySymlink"),installSkillForAgent=__name(async(skill,agentType,options={})=>{let agent=skillAgents[agentType],isGlobal=options.global??!1,cwd=options.cwd||process.cwd(),installMode=options.mode??"symlink";if(isGlobal&&agent.globalSkillsDir===void 0)return{success:!1,path:"",mode:installMode,error:`${agent.displayName} does not support global skill installation`};let skillName=sanitizeName(skill.name||basename3(skill.path)),canonicalBase=getCanonicalSkillsDir(isGlobal,cwd),canonicalDir=join10(canonicalBase,skillName),agentBase=getSkillAgentBaseDir(agentType,isGlobal,cwd),agentDir=join10(agentBase,skillName);if(!isPathSafe(canonicalBase,canonicalDir)||!isPathSafe(agentBase,agentDir))return{success:!1,path:agentDir,mode:installMode,error:"Invalid skill name: potential path traversal detected"};try{return installMode==="copy"?await installByCopy(skill,agentDir):await installBySymlink(skill,agentType,canonicalDir,agentDir,isGlobal)}catch(error){return{success:!1,path:agentDir,mode:installMode,error:toErrorMessage(error)}}},"installSkillForAgent");var OSC_RE=/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g,DCS_PM_APC_RE=/\x1b[P^_][\s\S]*?(?:\x1b\\)/g,CSI_RE=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/g,SIMPLE_ESC_RE=/\x1b[\x20-\x7e]/g,C1_RE=/[\x80-\x9f]/g,CONTROL_RE2=/[\x00-\x06\x07\x08\x0b\x0c\x0d-\x1a\x1c-\x1f\x7f]/g,stripTerminalEscapes=__name(input=>input.replace(OSC_RE,"").replace(DCS_PM_APC_RE,"").replace(CSI_RE,"").replace(SIMPLE_ESC_RE,"").replace(C1_RE,"").replace(CONTROL_RE2,""),"stripTerminalEscapes"),sanitizeMetadata=__name(input=>stripTerminalEscapes(input).replace(/[\r\n]+/g," ").trim(),"sanitizeMetadata"),PRIORITY_RELATIVE_PATHS=["","skills","skills/.curated","skills/.experimental","skills/.system",".agents/skills",".aider-desk/skills",".augment/skills",".bob/skills",".claude/skills",".cline/skills",".codeartsdoer/skills",".codebuddy/skills",".codemaker/skills",".codestudio/skills",".codex/skills",".commandcode/skills",".continue/skills",".cortex/skills",".crush/skills",".cursor/skills",".factory/skills",".forge/skills",".gemini/skills",".github/skills",".goose/skills",".iflow/skills",".junie/skills",".kilocode/skills",".kiro/skills",".kode/skills",".mcpjam/skills",".mux/skills",".neovate/skills",".openhands/skills",".pi/skills",".pochi/skills",".qoder/skills",".qwen/skills",".roo/skills",".rovodev/skills",".tabnine/agent/skills",".trae/skills",".vibe/skills",".windsurf/skills",".zencoder/skills"],hasSkillManifest=__name(async dir=>{try{return(await stat(join10(dir,SKILL_MANIFEST_FILE))).isFile()}catch{return!1}},"hasSkillManifest"),parseSkillManifest=__name(async manifestPath=>{try{let content2=await readFile4(manifestPath,"utf-8"),{data}=parseFrontmatter(content2);if(typeof data.name!="string"||typeof data.description!="string"||!data.name||!data.description)return null;let metadata=isPlainObject(data.metadata)?data.metadata:void 0;return{name:sanitizeMetadata(data.name),description:sanitizeMetadata(data.description),path:dirname6(manifestPath),rawContent:content2,metadata}}catch{return null}},"parseSkillManifest"),findSkillDirs=__name(async(dir,depth=0)=>{if(depth>5)return[];try{let[hasManifest,entries2]=await Promise.all([hasSkillManifest(dir),readdir(dir,{withFileTypes:!0}).catch(()=>[])]),currentDir=hasManifest?[dir]:[],subDirResults=await Promise.all(entries2.filter(entry=>entry.isDirectory()&&!SKIP_DISCOVERY_DIRS.has(entry.name)).map(entry=>findSkillDirs(join10(dir,entry.name),depth+1)));return[...currentDir,...subDirResults.flat()]}catch{return[]}},"findSkillDirs"),discoverSkills=__name(async(basePath,subpath,options)=>{if(subpath&&!isPathSafe(basePath,join10(basePath,subpath)))throw new Error(`Invalid subpath: "${subpath}" resolves outside the base directory. Subpath must not contain ".." segments that escape the base path.`);let searchPath=subpath?join10(basePath,subpath):basePath,seenNames=new Set,results=[],pluginGroupings=await getPluginGroupings(searchPath),enhanceSkill=__name(skill=>{let pluginName=pluginGroupings.get(resolve8(skill.path));return pluginName?{...skill,pluginName}:skill},"enhanceSkill"),pluginExtraDirs=await getPluginSkillPaths(searchPath);if(await hasSkillManifest(searchPath)){let skill=await parseSkillManifest(join10(searchPath,SKILL_MANIFEST_FILE));if(skill&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name),!options?.fullDepth))return results}let prioritySearchDirs=[...PRIORITY_RELATIVE_PATHS.map(relative3=>relative3?join10(searchPath,relative3):searchPath),...pluginExtraDirs];for(let dir of prioritySearchDirs)try{let entries2=await readdir(dir,{withFileTypes:!0});for(let entry of entries2){if(!entry.isDirectory())continue;let skillDir=join10(dir,entry.name);if(!await hasSkillManifest(skillDir))continue;let skill=await parseSkillManifest(join10(skillDir,SKILL_MANIFEST_FILE));skill&&!seenNames.has(skill.name)&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name))}}catch{}if(results.length===0||options?.fullDepth){let allSkillDirs=await findSkillDirs(searchPath);for(let skillDir of allSkillDirs){let skill=await parseSkillManifest(join10(skillDir,SKILL_MANIFEST_FILE));skill&&!seenNames.has(skill.name)&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name))}}return results},"discoverSkills"),getSkillDisplayName=__name(skill=>skill.name||basename3(skill.path),"getSkillDisplayName"),filterSkillsByName=__name((skills2,inputNames)=>{let normalizedInputs=inputNames.map(inputName=>inputName.toLowerCase());return skills2.filter(skill=>{let name=skill.name.toLowerCase(),displayName=getSkillDisplayName(skill).toLowerCase();return normalizedInputs.some(inputName=>inputName===name||inputName===displayName)})},"filterSkillsByName"),escapeRegex=__name(input=>input.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegex"),sanitizeSubpath=__name(subpath=>{let segments=subpath.replace(/\\/g,"/").split("/");for(let segment of segments)if(segment==="..")throw new Error(`Unsafe subpath: "${subpath}" contains path traversal segments. Subpaths must not contain ".." components.`);return subpath},"sanitizeSubpath"),HOST_CONFIGS=[{host:"github",domain:"github.com",prefix:"github:",treePrefix:"/tree/",anchorRepo:!1},{host:"gitlab",domain:"gitlab.com",prefix:"gitlab:",treePrefix:"/-/tree/",anchorRepo:!0}],HOST_BY_NAME=new Map(HOST_CONFIGS.map(config=>[config.host,config])),HOST_BY_DOMAIN=new Map(HOST_CONFIGS.map(config=>[config.domain,config])),SSH_URL_PATTERN=/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/,isLocalPath=__name(input=>isAbsolute3(input)||input.startsWith("./")||input.startsWith("../")||input==="."||input===".."||/^[a-zA-Z]:[/\\]/.test(input),"isLocalPath"),isShorthandCandidate=__name(input=>!input.includes(":")&&!input.startsWith(".")&&!input.startsWith("/"),"isShorthandCandidate"),buildHostedSource=__name(({host,owner,repo,ref,subpath,skillFilter})=>{let config=HOST_BY_NAME.get(host);if(!config)throw new Error(`Unknown host: ${host}`);let cleanRepo=repo.replace(/\.git$/,""),result={type:host,url:`https://${config.domain}/${owner}/${cleanRepo}.git`};return ref&&(result.ref=ref),subpath&&(result.subpath=sanitizeSubpath(subpath)),skillFilter&&(result.skillFilter=skillFilter),result},"buildHostedSource"),buildHostUrlPatterns=__name(config=>{let domain=escapeRegex(config.domain),treePrefix=escapeRegex(config.treePrefix),repoPattern=config.anchorRepo?`${domain}/([^/]+)/([^/]+?)(?:\\.git)?/?$`:`${domain}/([^/]+)/([^/]+)`;return{treeWithPath:new RegExp(`${domain}/([^/]+)/([^/]+)${treePrefix}([^/]+)/(.+)`),tree:new RegExp(`${domain}/([^/]+)/([^/]+)${treePrefix}([^/]+)$`),repo:new RegExp(repoPattern)}},"buildHostUrlPatterns"),HOST_URL_PATTERNS=new Map(HOST_CONFIGS.map(config=>[config.host,buildHostUrlPatterns(config)])),decodeFragmentValue=__name(value=>{try{return decodeURIComponent(value)}catch{return value}},"decodeFragmentValue"),looksLikeGitSource=__name(input=>{if(input.startsWith("git@")||HOST_CONFIGS.some(config=>input.startsWith(config.prefix)))return!0;if(input.startsWith("http://")||input.startsWith("https://"))try{let parsed=new URL(input),config=HOST_BY_DOMAIN.get(parsed.hostname);if(config){let treePrefix=escapeRegex(config.treePrefix);return new RegExp(`^/[^/]+/[^/]+(?:\\.git)?(?:${treePrefix}[^/]+(?:/.*)?)?/?$`).test(parsed.pathname)}}catch{return!1}return/^https?:\/\/.+\.git(?:$|[/?])/i.test(input)?!0:isShorthandCandidate(input)&&/^([^/]+)\/([^/]+)(?:\/(.+)|@(.+))?$/.test(input)},"looksLikeGitSource"),parseFragmentRef=__name(input=>{let hashIndex=input.indexOf("#");if(hashIndex<0)return{inputWithoutFragment:input};let inputWithoutFragment=input.slice(0,hashIndex),fragment=input.slice(hashIndex+1);if(!fragment||!looksLikeGitSource(inputWithoutFragment))return{inputWithoutFragment:input};let atIndex=fragment.indexOf("@");if(atIndex===-1)return{inputWithoutFragment,ref:decodeFragmentValue(fragment)};let ref=fragment.slice(0,atIndex),skillFilter=fragment.slice(atIndex+1);return{inputWithoutFragment,ref:ref?decodeFragmentValue(ref):void 0,skillFilter:skillFilter?decodeFragmentValue(skillFilter):void 0}},"parseFragmentRef"),isDirectSkillMdUrl=__name(input=>/^https?:\/\//.test(input)&&/\bSKILL\.md(?:$|\?|#)/i.test(input),"isDirectSkillMdUrl"),EXCLUDED_WELL_KNOWN_HOSTS=new Set(["raw.githubusercontent.com"]),isWellKnownCandidate=__name(input=>{if(!/^https?:\/\//.test(input))return!1;let parsed;try{parsed=new URL(input)}catch{return!1}return!(HOST_BY_DOMAIN.has(parsed.hostname)||EXCLUDED_WELL_KNOWN_HOSTS.has(parsed.hostname)||input.endsWith(".git")||isDirectSkillMdUrl(input))},"isWellKnownCandidate"),parseHostedShorthand=__name((rest,host,fragmentRef,fragmentSkillFilter)=>{let atSkillMatch=rest.match(/^([^/]+)\/([^/@]+)@(.+)$/);if(atSkillMatch){let[,owner,repo,skillFilter]=atSkillMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef,skillFilter:fragmentSkillFilter??skillFilter})}let shorthandMatch=rest.match(/^([^/]+)\/([^/]+)(?:\/(.+?))?\/?$/);if(shorthandMatch){let[,owner,repo,subpath]=shorthandMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef,subpath,skillFilter:fragmentSkillFilter})}return null},"parseHostedShorthand"),isHostnameAuthoritative=__name((input,expectedHostname)=>{if(!input.startsWith("http://")&&!input.startsWith("https://"))return!1;try{return new URL(input).hostname===expectedHostname}catch{return!1}},"isHostnameAuthoritative"),parseHostUrl=__name((input,host,fragmentRef)=>{let config=HOST_BY_NAME.get(host);if(!config||!isHostnameAuthoritative(input,config.domain))return null;let patterns=HOST_URL_PATTERNS.get(host);if(!patterns)return null;let treeWithPathMatch=input.match(patterns.treeWithPath);if(treeWithPathMatch){let[,owner,repo,ref,subpath]=treeWithPathMatch;return buildHostedSource({host,owner,repo,ref:ref||fragmentRef,subpath})}let treeMatch=input.match(patterns.tree);if(treeMatch){let[,owner,repo,ref]=treeMatch;return buildHostedSource({host,owner,repo,ref:ref||fragmentRef})}let repoMatch=input.match(patterns.repo);if(repoMatch){let[,owner,repo]=repoMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef})}return null},"parseHostUrl"),parseSshUrl=__name((input,fragmentRef,fragmentSkillFilter)=>{let match=input.match(SSH_URL_PATTERN);if(!match)return null;let[,sshHost]=match,result={type:HOST_BY_DOMAIN.get(sshHost)?.host??"git",url:input};return fragmentRef&&(result.ref=fragmentRef),fragmentSkillFilter&&(result.skillFilter=fragmentSkillFilter),result},"parseSshUrl"),parseSkillSource=__name(input=>{if(!input||input.trim().length===0)throw new Error("Invalid skill source: input is empty. Expected a local path, owner/repo shorthand, or URL.");if(isLocalPath(input)){let resolvedPath=resolve8(input);return{type:"local",url:resolvedPath,localPath:resolvedPath}}let{inputWithoutFragment,ref:fragmentRef,skillFilter:fragmentSkillFilter}=parseFragmentRef(input),normalized=inputWithoutFragment;for(let config of HOST_CONFIGS)if(normalized.startsWith(config.prefix)){let result2=parseHostedShorthand(normalized.slice(config.prefix.length),config.host,fragmentRef,fragmentSkillFilter);if(result2)return result2}if(normalized.startsWith("git@")){let sshResult=parseSshUrl(normalized,fragmentRef,fragmentSkillFilter);if(sshResult)return sshResult}for(let config of HOST_CONFIGS){let result2=parseHostUrl(normalized,config.host,fragmentRef);if(result2)return result2}if(isDirectSkillMdUrl(normalized))return{type:"url",url:normalized};if(isShorthandCandidate(normalized)){let result2=parseHostedShorthand(normalized,"github",fragmentRef,fragmentSkillFilter);if(result2)return result2}if(isWellKnownCandidate(normalized)){let wellKnownResult={type:"well-known",url:normalized};return fragmentSkillFilter&&(wellKnownResult.skillFilter=fragmentSkillFilter),wellKnownResult}let result={type:"git",url:normalized};return fragmentRef&&(result.ref=fragmentRef),result},"parseSkillSource"),resolveSource=__name(async parsed=>{if(parsed.type==="local"){if(!parsed.localPath)throw new Error("Local source is missing a resolved path");return{basePath:parsed.localPath}}if(parsed.type==="url"){let baseDir=await fetchSkillManifestFromUrl(parsed.url);return{basePath:baseDir,cleanup:__name(()=>cleanupTempDir(baseDir),"cleanup")}}if(parsed.type==="well-known"){let baseDir=await fetchWellKnownSkills(parsed.url);return{basePath:baseDir,skillFilter:parsed.skillFilter,cleanup:__name(()=>cleanupTempDir(baseDir),"cleanup")}}let cloneDir=await cloneRepo2(parsed.url,parsed.ref);return{basePath:cloneDir,subpath:parsed.subpath,skillFilter:parsed.skillFilter,cleanup:__name(()=>cleanupTempDir(cloneDir),"cleanup")}},"resolveSource"),resolveTargetAgents=__name(async requested=>{if(requested&&requested.length>0)return requested;let installed=await detectInstalledSkillAgents();return installed.length>0?installed:getUniversalSkillAgents()},"resolveTargetAgents"),resolveSkillFilters=__name((explicit,fromSource)=>{if(explicit&&explicit.length>0)return explicit;if(fromSource)return[fromSource]},"resolveSkillFilters"),installSkillsFromSource=__name(async options=>{let resolved=await resolveSource(parseSkillSource(options.source));try{let filters=resolveSkillFilters(options.skills,resolved.skillFilter),discovered=await discoverSkills(resolved.basePath,resolved.subpath),skills2=filters?filterSkillsByName(discovered,filters):discovered;if(skills2.length===0)return{installed:[],failed:[],skills:[]};let targetAgents=await resolveTargetAgents(options.agents),installed=[],failed=[];for(let skill of skills2)for(let agent of targetAgents){let result=await installSkillForAgent(skill,agent,{global:options.global,cwd:options.cwd,mode:options.mode});result.success?installed.push({skill:skill.name,agent,path:result.path,canonicalPath:result.canonicalPath,mode:result.mode,symlinkFailed:result.symlinkFailed}):failed.push({skill:skill.name,agent,error:result.error??"Unknown error"})}return{installed,failed,skills:skills2}}finally{await resolved.cleanup?.().catch(()=>{})}},"installSkillsFromSource");var import_yaml5=__toESM(require_dist3(),1);import{existsSync as existsSync10,mkdirSync as mkdirSync4,readFileSync as readFileSync9,writeFileSync as writeFileSync4}from"node:fs";import{homedir as homedir3,platform as platform3}from"node:os";import{dirname as dirname7,join as join11}from"node:path";var CharacterCodes;(function(CharacterCodes2){CharacterCodes2[CharacterCodes2.lineFeed=10]="lineFeed",CharacterCodes2[CharacterCodes2.carriageReturn=13]="carriageReturn",CharacterCodes2[CharacterCodes2.space=32]="space",CharacterCodes2[CharacterCodes2._0=48]="_0",CharacterCodes2[CharacterCodes2._1=49]="_1",CharacterCodes2[CharacterCodes2._2=50]="_2",CharacterCodes2[CharacterCodes2._3=51]="_3",CharacterCodes2[CharacterCodes2._4=52]="_4",CharacterCodes2[CharacterCodes2._5=53]="_5",CharacterCodes2[CharacterCodes2._6=54]="_6",CharacterCodes2[CharacterCodes2._7=55]="_7",CharacterCodes2[CharacterCodes2._8=56]="_8",CharacterCodes2[CharacterCodes2._9=57]="_9",CharacterCodes2[CharacterCodes2.a=97]="a",CharacterCodes2[CharacterCodes2.b=98]="b",CharacterCodes2[CharacterCodes2.c=99]="c",CharacterCodes2[CharacterCodes2.d=100]="d",CharacterCodes2[CharacterCodes2.e=101]="e",CharacterCodes2[CharacterCodes2.f=102]="f",CharacterCodes2[CharacterCodes2.g=103]="g",CharacterCodes2[CharacterCodes2.h=104]="h",CharacterCodes2[CharacterCodes2.i=105]="i",CharacterCodes2[CharacterCodes2.j=106]="j",CharacterCodes2[CharacterCodes2.k=107]="k",CharacterCodes2[CharacterCodes2.l=108]="l",CharacterCodes2[CharacterCodes2.m=109]="m",CharacterCodes2[CharacterCodes2.n=110]="n",CharacterCodes2[CharacterCodes2.o=111]="o",CharacterCodes2[CharacterCodes2.p=112]="p",CharacterCodes2[CharacterCodes2.q=113]="q",CharacterCodes2[CharacterCodes2.r=114]="r",CharacterCodes2[CharacterCodes2.s=115]="s",CharacterCodes2[CharacterCodes2.t=116]="t",CharacterCodes2[CharacterCodes2.u=117]="u",CharacterCodes2[CharacterCodes2.v=118]="v",CharacterCodes2[CharacterCodes2.w=119]="w",CharacterCodes2[CharacterCodes2.x=120]="x",CharacterCodes2[CharacterCodes2.y=121]="y",CharacterCodes2[CharacterCodes2.z=122]="z",CharacterCodes2[CharacterCodes2.A=65]="A",CharacterCodes2[CharacterCodes2.B=66]="B",CharacterCodes2[CharacterCodes2.C=67]="C",CharacterCodes2[CharacterCodes2.D=68]="D",CharacterCodes2[CharacterCodes2.E=69]="E",CharacterCodes2[CharacterCodes2.F=70]="F",CharacterCodes2[CharacterCodes2.G=71]="G",CharacterCodes2[CharacterCodes2.H=72]="H",CharacterCodes2[CharacterCodes2.I=73]="I",CharacterCodes2[CharacterCodes2.J=74]="J",CharacterCodes2[CharacterCodes2.K=75]="K",CharacterCodes2[CharacterCodes2.L=76]="L",CharacterCodes2[CharacterCodes2.M=77]="M",CharacterCodes2[CharacterCodes2.N=78]="N",CharacterCodes2[CharacterCodes2.O=79]="O",CharacterCodes2[CharacterCodes2.P=80]="P",CharacterCodes2[CharacterCodes2.Q=81]="Q",CharacterCodes2[CharacterCodes2.R=82]="R",CharacterCodes2[CharacterCodes2.S=83]="S",CharacterCodes2[CharacterCodes2.T=84]="T",CharacterCodes2[CharacterCodes2.U=85]="U",CharacterCodes2[CharacterCodes2.V=86]="V",CharacterCodes2[CharacterCodes2.W=87]="W",CharacterCodes2[CharacterCodes2.X=88]="X",CharacterCodes2[CharacterCodes2.Y=89]="Y",CharacterCodes2[CharacterCodes2.Z=90]="Z",CharacterCodes2[CharacterCodes2.asterisk=42]="asterisk",CharacterCodes2[CharacterCodes2.backslash=92]="backslash",CharacterCodes2[CharacterCodes2.closeBrace=125]="closeBrace",CharacterCodes2[CharacterCodes2.closeBracket=93]="closeBracket",CharacterCodes2[CharacterCodes2.colon=58]="colon",CharacterCodes2[CharacterCodes2.comma=44]="comma",CharacterCodes2[CharacterCodes2.dot=46]="dot",CharacterCodes2[CharacterCodes2.doubleQuote=34]="doubleQuote",CharacterCodes2[CharacterCodes2.minus=45]="minus",CharacterCodes2[CharacterCodes2.openBrace=123]="openBrace",CharacterCodes2[CharacterCodes2.openBracket=91]="openBracket",CharacterCodes2[CharacterCodes2.plus=43]="plus",CharacterCodes2[CharacterCodes2.slash=47]="slash",CharacterCodes2[CharacterCodes2.formFeed=12]="formFeed",CharacterCodes2[CharacterCodes2.tab=9]="tab"})(CharacterCodes||(CharacterCodes={}));var cachedSpaces=new Array(20).fill(0).map((_,index)=>" ".repeat(index)),maxCachedValues=200,cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>`
|
|
717
|
+
`),url,"auth"):new GitCloneError(`Failed to clone ${url}: ${stderr.trim()||"unknown error"}`,url)},"cloneRepo"),cleanupTempDir=__name(async dir=>{let normalizedDir=normalize(resolve8(dir)),normalizedTmpDir=normalize(resolve8(tmpdir2()));if(!normalizedDir.startsWith(normalizedTmpDir+sep)&&normalizedDir!==normalizedTmpDir)throw new Error("Attempted to clean up directory outside of temp directory");await rm(dir,{recursive:!0,force:!0})},"cleanupTempDir"),getCanonicalSkillsDir=__name((isGlobal,cwd)=>join10(isGlobal?homedir2():cwd||process.cwd(),CANONICAL_SKILLS_DIR),"getCanonicalSkillsDir"),getSkillAgentBaseDir=__name((agentType,isGlobal,cwd)=>{if(isUniversalSkillAgent(agentType))return getCanonicalSkillsDir(isGlobal,cwd);let agent=getSkillAgentConfig(agentType),baseDir=isGlobal?homedir2():cwd||process.cwd();return isGlobal?agent.globalSkillsDir??join10(baseDir,agent.skillsDir):join10(baseDir,agent.skillsDir)},"getSkillAgentBaseDir"),cleanAndCreateDirectory=__name(async path52=>{await rm(path52,{recursive:!0,force:!0}).catch(()=>{}),await mkdir(path52,{recursive:!0})},"cleanAndCreateDirectory"),resolveSymlinkTarget=__name((linkPath,linkTarget)=>resolve8(dirname6(linkPath),linkTarget),"resolveSymlinkTarget"),resolveParentSymlinks=__name(async path52=>{let resolved=resolve8(path52),parentDir=dirname6(resolved),name=basename3(resolved);try{return join10(await realpath(parentDir),name)}catch{return resolved}},"resolveParentSymlinks"),isPathInsideBase=__name((basePath,targetPath)=>{let normalizedBase=resolve8(basePath),normalizedTarget=resolve8(targetPath);return normalizedTarget===normalizedBase||normalizedTarget.startsWith(normalizedBase+sep)},"isPathInsideBase"),copyDirectory=__name(async(src,dest,rootSrc=src)=>{await mkdir(dest,{recursive:!0});let entries2=await readdir(src,{withFileTypes:!0});await Promise.all(entries2.filter(entry=>!COPY_EXCLUDE_FILES.has(entry.name)&&!(entry.isDirectory()&©_EXCLUDE_DIRS.has(entry.name))).map(async entry=>{let srcPath=join10(src,entry.name),destPath=join10(dest,entry.name);if(entry.isSymbolicLink()){let linkRealPath=await realpath(srcPath).catch(()=>null);if(!linkRealPath||!isPathInsideBase(rootSrc,linkRealPath))return;await cp(srcPath,destPath,{dereference:!0,recursive:!0});return}if(entry.isDirectory()){await copyDirectory(srcPath,destPath,rootSrc);return}await cp(srcPath,destPath,{dereference:!1,recursive:!0})}))},"copyDirectory"),isLoopError=__name(error=>!!(error&&typeof error=="object"&&"code"in error&&error.code==="ELOOP"),"isLoopError"),createSymlink=__name(async(target,linkPath)=>{try{let resolvedTarget=resolve8(target),resolvedLinkPath=resolve8(linkPath),[realTarget,realLinkPath]=await Promise.all([realpath(resolvedTarget).catch(()=>resolvedTarget),realpath(resolvedLinkPath).catch(()=>resolvedLinkPath)]);if(realTarget===realLinkPath)return!0;let[realTargetWithParents,realLinkPathWithParents]=await Promise.all([resolveParentSymlinks(target),resolveParentSymlinks(linkPath)]);if(realTargetWithParents===realLinkPathWithParents)return!0;try{if((await lstat(linkPath)).isSymbolicLink()){if(resolveSymlinkTarget(linkPath,await readlink(linkPath))===resolvedTarget)return!0;await rm(linkPath)}else await rm(linkPath,{recursive:!0})}catch(error){isLoopError(error)&&await rm(linkPath,{force:!0}).catch(()=>{})}let linkDir=dirname6(linkPath);return await mkdir(linkDir,{recursive:!0}),await symlink(relative2(await resolveParentSymlinks(linkDir),target),linkPath,platform2()==="win32"?"junction":void 0),!0}catch{return!1}},"createSymlink"),installByCopy=__name(async(skill,destination)=>(await cleanAndCreateDirectory(destination),await copyDirectory(skill.path,destination),{success:!0,path:destination,mode:"copy"}),"installByCopy"),installBySymlink=__name(async(skill,agentType,canonicalDir,agentDir,isGlobal)=>(await cleanAndCreateDirectory(canonicalDir),await copyDirectory(skill.path,canonicalDir),isGlobal&&isUniversalSkillAgent(agentType)?{success:!0,path:canonicalDir,canonicalPath:canonicalDir,mode:"symlink"}:await createSymlink(canonicalDir,agentDir)?{success:!0,path:agentDir,canonicalPath:canonicalDir,mode:"symlink"}:(await cleanAndCreateDirectory(agentDir),await copyDirectory(skill.path,agentDir),{success:!0,path:agentDir,canonicalPath:canonicalDir,mode:"symlink",symlinkFailed:!0})),"installBySymlink"),installSkillForAgent=__name(async(skill,agentType,options={})=>{let agent=skillAgents[agentType],isGlobal=options.global??!1,cwd=options.cwd||process.cwd(),installMode=options.mode??"symlink";if(isGlobal&&agent.globalSkillsDir===void 0)return{success:!1,path:"",mode:installMode,error:`${agent.displayName} does not support global skill installation`};let skillName=sanitizeName(skill.name||basename3(skill.path)),canonicalBase=getCanonicalSkillsDir(isGlobal,cwd),canonicalDir=join10(canonicalBase,skillName),agentBase=getSkillAgentBaseDir(agentType,isGlobal,cwd),agentDir=join10(agentBase,skillName);if(!isPathSafe(canonicalBase,canonicalDir)||!isPathSafe(agentBase,agentDir))return{success:!1,path:agentDir,mode:installMode,error:"Invalid skill name: potential path traversal detected"};try{return installMode==="copy"?await installByCopy(skill,agentDir):await installBySymlink(skill,agentType,canonicalDir,agentDir,isGlobal)}catch(error){return{success:!1,path:agentDir,mode:installMode,error:toErrorMessage(error)}}},"installSkillForAgent");var OSC_RE=/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g,DCS_PM_APC_RE=/\x1b[P^_][\s\S]*?(?:\x1b\\)/g,CSI_RE=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/g,SIMPLE_ESC_RE=/\x1b[\x20-\x7e]/g,C1_RE=/[\x80-\x9f]/g,CONTROL_RE2=/[\x00-\x06\x07\x08\x0b\x0c\x0d-\x1a\x1c-\x1f\x7f]/g,stripTerminalEscapes=__name(input=>input.replace(OSC_RE,"").replace(DCS_PM_APC_RE,"").replace(CSI_RE,"").replace(SIMPLE_ESC_RE,"").replace(C1_RE,"").replace(CONTROL_RE2,""),"stripTerminalEscapes"),sanitizeMetadata=__name(input=>stripTerminalEscapes(input).replace(/[\r\n]+/g," ").trim(),"sanitizeMetadata"),PRIORITY_RELATIVE_PATHS=["","skills","skills/.curated","skills/.experimental","skills/.system",".agents/skills",".aider-desk/skills",".augment/skills",".bob/skills",".claude/skills",".cline/skills",".codeartsdoer/skills",".codebuddy/skills",".codemaker/skills",".codestudio/skills",".codex/skills",".commandcode/skills",".continue/skills",".cortex/skills",".crush/skills",".cursor/skills",".factory/skills",".forge/skills",".gemini/skills",".github/skills",".goose/skills",".iflow/skills",".junie/skills",".kilocode/skills",".kiro/skills",".kode/skills",".mcpjam/skills",".mux/skills",".neovate/skills",".openhands/skills",".pi/skills",".pochi/skills",".qoder/skills",".qwen/skills",".roo/skills",".rovodev/skills",".tabnine/agent/skills",".trae/skills",".vibe/skills",".windsurf/skills",".zencoder/skills"],hasSkillManifest=__name(async dir=>{try{return(await stat(join10(dir,SKILL_MANIFEST_FILE))).isFile()}catch{return!1}},"hasSkillManifest"),parseSkillManifest=__name(async manifestPath=>{try{let content2=await readFile4(manifestPath,"utf-8"),{data}=parseFrontmatter(content2);if(typeof data.name!="string"||typeof data.description!="string"||!data.name||!data.description)return null;let metadata=isPlainObject(data.metadata)?data.metadata:void 0;return{name:sanitizeMetadata(data.name),description:sanitizeMetadata(data.description),path:dirname6(manifestPath),rawContent:content2,metadata}}catch{return null}},"parseSkillManifest"),findSkillDirs=__name(async(dir,depth=0)=>{if(depth>5)return[];try{let[hasManifest,entries2]=await Promise.all([hasSkillManifest(dir),readdir(dir,{withFileTypes:!0}).catch(()=>[])]),currentDir=hasManifest?[dir]:[],subDirResults=await Promise.all(entries2.filter(entry=>entry.isDirectory()&&!SKIP_DISCOVERY_DIRS.has(entry.name)).map(entry=>findSkillDirs(join10(dir,entry.name),depth+1)));return[...currentDir,...subDirResults.flat()]}catch{return[]}},"findSkillDirs"),discoverSkills=__name(async(basePath,subpath,options)=>{if(subpath&&!isPathSafe(basePath,join10(basePath,subpath)))throw new Error(`Invalid subpath: "${subpath}" resolves outside the base directory. Subpath must not contain ".." segments that escape the base path.`);let searchPath=subpath?join10(basePath,subpath):basePath,seenNames=new Set,results=[],pluginGroupings=await getPluginGroupings(searchPath),enhanceSkill=__name(skill=>{let pluginName=pluginGroupings.get(resolve8(skill.path));return pluginName?{...skill,pluginName}:skill},"enhanceSkill"),pluginExtraDirs=await getPluginSkillPaths(searchPath);if(await hasSkillManifest(searchPath)){let skill=await parseSkillManifest(join10(searchPath,SKILL_MANIFEST_FILE));if(skill&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name),!options?.fullDepth))return results}let prioritySearchDirs=[...PRIORITY_RELATIVE_PATHS.map(relative3=>relative3?join10(searchPath,relative3):searchPath),...pluginExtraDirs];for(let dir of prioritySearchDirs)try{let entries2=await readdir(dir,{withFileTypes:!0});for(let entry of entries2){if(!entry.isDirectory())continue;let skillDir=join10(dir,entry.name);if(!await hasSkillManifest(skillDir))continue;let skill=await parseSkillManifest(join10(skillDir,SKILL_MANIFEST_FILE));skill&&!seenNames.has(skill.name)&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name))}}catch{}if(results.length===0||options?.fullDepth){let allSkillDirs=await findSkillDirs(searchPath);for(let skillDir of allSkillDirs){let skill=await parseSkillManifest(join10(skillDir,SKILL_MANIFEST_FILE));skill&&!seenNames.has(skill.name)&&(results.push(enhanceSkill(skill)),seenNames.add(skill.name))}}return results},"discoverSkills"),getSkillDisplayName=__name(skill=>skill.name||basename3(skill.path),"getSkillDisplayName"),filterSkillsByName=__name((skills2,inputNames)=>{let normalizedInputs=inputNames.map(inputName=>inputName.toLowerCase());return skills2.filter(skill=>{let name=skill.name.toLowerCase(),displayName=getSkillDisplayName(skill).toLowerCase();return normalizedInputs.some(inputName=>inputName===name||inputName===displayName)})},"filterSkillsByName"),escapeRegex=__name(input=>input.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegex"),sanitizeSubpath=__name(subpath=>{let segments=subpath.replace(/\\/g,"/").split("/");for(let segment of segments)if(segment==="..")throw new Error(`Unsafe subpath: "${subpath}" contains path traversal segments. Subpaths must not contain ".." components.`);return subpath},"sanitizeSubpath"),HOST_CONFIGS=[{host:"github",domain:"github.com",prefix:"github:",treePrefix:"/tree/",anchorRepo:!1},{host:"gitlab",domain:"gitlab.com",prefix:"gitlab:",treePrefix:"/-/tree/",anchorRepo:!0}],HOST_BY_NAME=new Map(HOST_CONFIGS.map(config=>[config.host,config])),HOST_BY_DOMAIN=new Map(HOST_CONFIGS.map(config=>[config.domain,config])),SSH_URL_PATTERN=/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/,isLocalPath=__name(input=>isAbsolute3(input)||input.startsWith("./")||input.startsWith("../")||input==="."||input===".."||/^[a-zA-Z]:[/\\]/.test(input),"isLocalPath"),isShorthandCandidate=__name(input=>!input.includes(":")&&!input.startsWith(".")&&!input.startsWith("/"),"isShorthandCandidate"),buildHostedSource=__name(({host,owner,repo,ref,subpath,skillFilter})=>{let config=HOST_BY_NAME.get(host);if(!config)throw new Error(`Unknown host: ${host}`);let cleanRepo=repo.replace(/\.git$/,""),result={type:host,url:`https://${config.domain}/${owner}/${cleanRepo}.git`};return ref&&(result.ref=ref),subpath&&(result.subpath=sanitizeSubpath(subpath)),skillFilter&&(result.skillFilter=skillFilter),result},"buildHostedSource"),buildHostUrlPatterns=__name(config=>{let domain=escapeRegex(config.domain),treePrefix=escapeRegex(config.treePrefix),repoPattern=config.anchorRepo?`${domain}/([^/]+)/([^/]+?)(?:\\.git)?/?$`:`${domain}/([^/]+)/([^/]+)`;return{treeWithPath:new RegExp(`${domain}/([^/]+)/([^/]+)${treePrefix}([^/]+)/(.+)`),tree:new RegExp(`${domain}/([^/]+)/([^/]+)${treePrefix}([^/]+)$`),repo:new RegExp(repoPattern)}},"buildHostUrlPatterns"),HOST_URL_PATTERNS=new Map(HOST_CONFIGS.map(config=>[config.host,buildHostUrlPatterns(config)])),decodeFragmentValue=__name(value=>{try{return decodeURIComponent(value)}catch{return value}},"decodeFragmentValue"),looksLikeGitSource=__name(input=>{if(input.startsWith("git@")||HOST_CONFIGS.some(config=>input.startsWith(config.prefix)))return!0;if(input.startsWith("http://")||input.startsWith("https://"))try{let parsed=new URL(input),config=HOST_BY_DOMAIN.get(parsed.hostname);if(config){let treePrefix=escapeRegex(config.treePrefix);return new RegExp(`^/[^/]+/[^/]+(?:\\.git)?(?:${treePrefix}[^/]+(?:/.*)?)?/?$`).test(parsed.pathname)}}catch{return!1}return/^https?:\/\/.+\.git(?:$|[/?])/i.test(input)?!0:isShorthandCandidate(input)&&/^([^/]+)\/([^/]+)(?:\/(.+)|@(.+))?$/.test(input)},"looksLikeGitSource"),parseFragmentRef=__name(input=>{let hashIndex=input.indexOf("#");if(hashIndex<0)return{inputWithoutFragment:input};let inputWithoutFragment=input.slice(0,hashIndex),fragment=input.slice(hashIndex+1);if(!fragment||!looksLikeGitSource(inputWithoutFragment))return{inputWithoutFragment:input};let atIndex=fragment.indexOf("@");if(atIndex===-1)return{inputWithoutFragment,ref:decodeFragmentValue(fragment)};let ref=fragment.slice(0,atIndex),skillFilter=fragment.slice(atIndex+1);return{inputWithoutFragment,ref:ref?decodeFragmentValue(ref):void 0,skillFilter:skillFilter?decodeFragmentValue(skillFilter):void 0}},"parseFragmentRef"),isDirectSkillMdUrl=__name(input=>/^https?:\/\//.test(input)&&/\bSKILL\.md(?:$|\?|#)/i.test(input),"isDirectSkillMdUrl"),EXCLUDED_WELL_KNOWN_HOSTS=new Set(["raw.githubusercontent.com"]),isWellKnownCandidate=__name(input=>{if(!/^https?:\/\//.test(input))return!1;let parsed;try{parsed=new URL(input)}catch{return!1}return!(HOST_BY_DOMAIN.has(parsed.hostname)||EXCLUDED_WELL_KNOWN_HOSTS.has(parsed.hostname)||input.endsWith(".git")||isDirectSkillMdUrl(input))},"isWellKnownCandidate"),parseHostedShorthand=__name((rest,host,fragmentRef,fragmentSkillFilter)=>{let atSkillMatch=rest.match(/^([^/]+)\/([^/@]+)@(.+)$/);if(atSkillMatch){let[,owner,repo,skillFilter]=atSkillMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef,skillFilter:fragmentSkillFilter??skillFilter})}let shorthandMatch=rest.match(/^([^/]+)\/([^/]+)(?:\/(.+?))?\/?$/);if(shorthandMatch){let[,owner,repo,subpath]=shorthandMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef,subpath,skillFilter:fragmentSkillFilter})}return null},"parseHostedShorthand"),isHostnameAuthoritative=__name((input,expectedHostname)=>{if(!input.startsWith("http://")&&!input.startsWith("https://"))return!1;try{return new URL(input).hostname===expectedHostname}catch{return!1}},"isHostnameAuthoritative"),parseHostUrl=__name((input,host,fragmentRef)=>{let config=HOST_BY_NAME.get(host);if(!config||!isHostnameAuthoritative(input,config.domain))return null;let patterns=HOST_URL_PATTERNS.get(host);if(!patterns)return null;let treeWithPathMatch=input.match(patterns.treeWithPath);if(treeWithPathMatch){let[,owner,repo,ref,subpath]=treeWithPathMatch;return buildHostedSource({host,owner,repo,ref:ref||fragmentRef,subpath})}let treeMatch=input.match(patterns.tree);if(treeMatch){let[,owner,repo,ref]=treeMatch;return buildHostedSource({host,owner,repo,ref:ref||fragmentRef})}let repoMatch=input.match(patterns.repo);if(repoMatch){let[,owner,repo]=repoMatch;return buildHostedSource({host,owner,repo,ref:fragmentRef})}return null},"parseHostUrl"),parseSshUrl=__name((input,fragmentRef,fragmentSkillFilter)=>{let match=input.match(SSH_URL_PATTERN);if(!match)return null;let[,sshHost]=match,result={type:HOST_BY_DOMAIN.get(sshHost)?.host??"git",url:input};return fragmentRef&&(result.ref=fragmentRef),fragmentSkillFilter&&(result.skillFilter=fragmentSkillFilter),result},"parseSshUrl"),parseSkillSource=__name(input=>{if(!input||input.trim().length===0)throw new Error("Invalid skill source: input is empty. Expected a local path, owner/repo shorthand, or URL.");if(isLocalPath(input)){let resolvedPath=resolve8(input);return{type:"local",url:resolvedPath,localPath:resolvedPath}}let{inputWithoutFragment,ref:fragmentRef,skillFilter:fragmentSkillFilter}=parseFragmentRef(input),normalized=inputWithoutFragment;for(let config of HOST_CONFIGS)if(normalized.startsWith(config.prefix)){let result2=parseHostedShorthand(normalized.slice(config.prefix.length),config.host,fragmentRef,fragmentSkillFilter);if(result2)return result2}if(normalized.startsWith("git@")){let sshResult=parseSshUrl(normalized,fragmentRef,fragmentSkillFilter);if(sshResult)return sshResult}for(let config of HOST_CONFIGS){let result2=parseHostUrl(normalized,config.host,fragmentRef);if(result2)return result2}if(isDirectSkillMdUrl(normalized))return{type:"url",url:normalized};if(isShorthandCandidate(normalized)){let result2=parseHostedShorthand(normalized,"github",fragmentRef,fragmentSkillFilter);if(result2)return result2}if(isWellKnownCandidate(normalized)){let wellKnownResult={type:"well-known",url:normalized};return fragmentSkillFilter&&(wellKnownResult.skillFilter=fragmentSkillFilter),wellKnownResult}let result={type:"git",url:normalized};return fragmentRef&&(result.ref=fragmentRef),result},"parseSkillSource"),resolveSource=__name(async parsed=>{if(parsed.type==="local"){if(!parsed.localPath)throw new Error("Local source is missing a resolved path");return{basePath:parsed.localPath}}if(parsed.type==="url"){let baseDir=await fetchSkillManifestFromUrl(parsed.url);return{basePath:baseDir,cleanup:__name(()=>cleanupTempDir(baseDir),"cleanup")}}if(parsed.type==="well-known"){let baseDir=await fetchWellKnownSkills(parsed.url);return{basePath:baseDir,skillFilter:parsed.skillFilter,cleanup:__name(()=>cleanupTempDir(baseDir),"cleanup")}}let cloneDir=await cloneRepo2(parsed.url,parsed.ref);return{basePath:cloneDir,subpath:parsed.subpath,skillFilter:parsed.skillFilter,cleanup:__name(()=>cleanupTempDir(cloneDir),"cleanup")}},"resolveSource"),resolveTargetAgents=__name(async requested=>{if(requested&&requested.length>0)return requested;let installed=await detectInstalledSkillAgents();return installed.length>0?installed:getUniversalSkillAgents()},"resolveTargetAgents"),resolveSkillFilters=__name((explicit,fromSource)=>{if(explicit&&explicit.length>0)return explicit;if(fromSource)return[fromSource]},"resolveSkillFilters"),installSkillsFromSource=__name(async options=>{let resolved=await resolveSource(parseSkillSource(options.source));try{let filters=resolveSkillFilters(options.skills,resolved.skillFilter),discovered=await discoverSkills(resolved.basePath,resolved.subpath),skills2=filters?filterSkillsByName(discovered,filters):discovered;if(skills2.length===0)return{installed:[],failed:[],skills:[]};let targetAgents=await resolveTargetAgents(options.agents),installed=[],failed=[];for(let skill of skills2)for(let agent of targetAgents){let result=await installSkillForAgent(skill,agent,{global:options.global,cwd:options.cwd,mode:options.mode});result.success?installed.push({skill:skill.name,agent,path:result.path,canonicalPath:result.canonicalPath,mode:result.mode,symlinkFailed:result.symlinkFailed}):failed.push({skill:skill.name,agent,error:result.error??"Unknown error"})}return{installed,failed,skills:skills2}}finally{await resolved.cleanup?.().catch(()=>{})}},"installSkillsFromSource");var import_yaml5=__toESM(require_dist3(),1);import{existsSync as existsSync10,mkdirSync as mkdirSync4,readFileSync as readFileSync10,writeFileSync as writeFileSync4}from"node:fs";import{homedir as homedir3,platform as platform3}from"node:os";import{dirname as dirname7,join as join11}from"node:path";var CharacterCodes;(function(CharacterCodes2){CharacterCodes2[CharacterCodes2.lineFeed=10]="lineFeed",CharacterCodes2[CharacterCodes2.carriageReturn=13]="carriageReturn",CharacterCodes2[CharacterCodes2.space=32]="space",CharacterCodes2[CharacterCodes2._0=48]="_0",CharacterCodes2[CharacterCodes2._1=49]="_1",CharacterCodes2[CharacterCodes2._2=50]="_2",CharacterCodes2[CharacterCodes2._3=51]="_3",CharacterCodes2[CharacterCodes2._4=52]="_4",CharacterCodes2[CharacterCodes2._5=53]="_5",CharacterCodes2[CharacterCodes2._6=54]="_6",CharacterCodes2[CharacterCodes2._7=55]="_7",CharacterCodes2[CharacterCodes2._8=56]="_8",CharacterCodes2[CharacterCodes2._9=57]="_9",CharacterCodes2[CharacterCodes2.a=97]="a",CharacterCodes2[CharacterCodes2.b=98]="b",CharacterCodes2[CharacterCodes2.c=99]="c",CharacterCodes2[CharacterCodes2.d=100]="d",CharacterCodes2[CharacterCodes2.e=101]="e",CharacterCodes2[CharacterCodes2.f=102]="f",CharacterCodes2[CharacterCodes2.g=103]="g",CharacterCodes2[CharacterCodes2.h=104]="h",CharacterCodes2[CharacterCodes2.i=105]="i",CharacterCodes2[CharacterCodes2.j=106]="j",CharacterCodes2[CharacterCodes2.k=107]="k",CharacterCodes2[CharacterCodes2.l=108]="l",CharacterCodes2[CharacterCodes2.m=109]="m",CharacterCodes2[CharacterCodes2.n=110]="n",CharacterCodes2[CharacterCodes2.o=111]="o",CharacterCodes2[CharacterCodes2.p=112]="p",CharacterCodes2[CharacterCodes2.q=113]="q",CharacterCodes2[CharacterCodes2.r=114]="r",CharacterCodes2[CharacterCodes2.s=115]="s",CharacterCodes2[CharacterCodes2.t=116]="t",CharacterCodes2[CharacterCodes2.u=117]="u",CharacterCodes2[CharacterCodes2.v=118]="v",CharacterCodes2[CharacterCodes2.w=119]="w",CharacterCodes2[CharacterCodes2.x=120]="x",CharacterCodes2[CharacterCodes2.y=121]="y",CharacterCodes2[CharacterCodes2.z=122]="z",CharacterCodes2[CharacterCodes2.A=65]="A",CharacterCodes2[CharacterCodes2.B=66]="B",CharacterCodes2[CharacterCodes2.C=67]="C",CharacterCodes2[CharacterCodes2.D=68]="D",CharacterCodes2[CharacterCodes2.E=69]="E",CharacterCodes2[CharacterCodes2.F=70]="F",CharacterCodes2[CharacterCodes2.G=71]="G",CharacterCodes2[CharacterCodes2.H=72]="H",CharacterCodes2[CharacterCodes2.I=73]="I",CharacterCodes2[CharacterCodes2.J=74]="J",CharacterCodes2[CharacterCodes2.K=75]="K",CharacterCodes2[CharacterCodes2.L=76]="L",CharacterCodes2[CharacterCodes2.M=77]="M",CharacterCodes2[CharacterCodes2.N=78]="N",CharacterCodes2[CharacterCodes2.O=79]="O",CharacterCodes2[CharacterCodes2.P=80]="P",CharacterCodes2[CharacterCodes2.Q=81]="Q",CharacterCodes2[CharacterCodes2.R=82]="R",CharacterCodes2[CharacterCodes2.S=83]="S",CharacterCodes2[CharacterCodes2.T=84]="T",CharacterCodes2[CharacterCodes2.U=85]="U",CharacterCodes2[CharacterCodes2.V=86]="V",CharacterCodes2[CharacterCodes2.W=87]="W",CharacterCodes2[CharacterCodes2.X=88]="X",CharacterCodes2[CharacterCodes2.Y=89]="Y",CharacterCodes2[CharacterCodes2.Z=90]="Z",CharacterCodes2[CharacterCodes2.asterisk=42]="asterisk",CharacterCodes2[CharacterCodes2.backslash=92]="backslash",CharacterCodes2[CharacterCodes2.closeBrace=125]="closeBrace",CharacterCodes2[CharacterCodes2.closeBracket=93]="closeBracket",CharacterCodes2[CharacterCodes2.colon=58]="colon",CharacterCodes2[CharacterCodes2.comma=44]="comma",CharacterCodes2[CharacterCodes2.dot=46]="dot",CharacterCodes2[CharacterCodes2.doubleQuote=34]="doubleQuote",CharacterCodes2[CharacterCodes2.minus=45]="minus",CharacterCodes2[CharacterCodes2.openBrace=123]="openBrace",CharacterCodes2[CharacterCodes2.openBracket=91]="openBracket",CharacterCodes2[CharacterCodes2.plus=43]="plus",CharacterCodes2[CharacterCodes2.slash=47]="slash",CharacterCodes2[CharacterCodes2.formFeed=12]="formFeed",CharacterCodes2[CharacterCodes2.tab=9]="tab"})(CharacterCodes||(CharacterCodes={}));var cachedSpaces=new Array(20).fill(0).map((_,index)=>" ".repeat(index)),maxCachedValues=200,cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>`
|
|
718
718
|
`+" ".repeat(index)),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>"\r"+" ".repeat(index)),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>`\r
|
|
719
719
|
`+" ".repeat(index))}," ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>`
|
|
720
720
|
`+" ".repeat(index)),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>"\r"+" ".repeat(index)),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>`\r
|
|
@@ -832,7 +832,7 @@ ${V2(this.state)} ${opts.message}
|
|
|
832
832
|
</main>
|
|
833
833
|
<script>setTimeout(function(){window.close();},800);</script>
|
|
834
834
|
</body>
|
|
835
|
-
</html>`}__name(renderSignedInPage,"renderSignedInPage");import{execFile as execFile9,spawnSync as spawnSync2}from"node:child_process";import{readFile as readFile5,writeFile as writeFile2}from"node:fs/promises";import path36 from"node:path";import{promisify as promisify9}from"node:util";init_esm();init_dist();init_auth();init_sdk_transport();init_project_services();init_git_credential_setup();init_git();import fs35 from"node:fs";import{createRequire as
|
|
835
|
+
</html>`}__name(renderSignedInPage,"renderSignedInPage");import{execFile as execFile9,spawnSync as spawnSync2}from"node:child_process";import{readFile as readFile5,writeFile as writeFile2}from"node:fs/promises";import path36 from"node:path";import{promisify as promisify9}from"node:util";init_esm();init_dist();init_auth();init_sdk_transport();init_project_services();init_git_credential_setup();init_git();import fs35 from"node:fs";import{createRequire as createRequire4}from"node:module";import path35 from"node:path";init_dist();init_config();init_project();init_version();var SKILLS_ROOT=path35.resolve(CLI_ROOT,"assets","skills"),BOOTSTRAP_SKILL_NAME="fimo",BOOTSTRAP_SKILL_SOURCE=path35.join(SKILLS_ROOT,BOOTSTRAP_SKILL_NAME);var STREAMED_REFERENCE_HINT="Reference paths in this document are identifiers, not project files. Load one with `fimo skills get <skill> --ref <reference>`.",STALE_GLOBAL_SKILL_NAMES=["fimo-cli","fimo-studio","fimo-migration","fimo-migrate","fimo-source-migrate"],DETECTABLE_FIMO_SKILL_NAMES=[BOOTSTRAP_SKILL_NAME,...STALE_GLOBAL_SKILL_NAMES];function isPrettyMode(){return currentMode().format==="pretty"}__name(isPrettyMode,"isPrettyMode");async function runSkillsInstall(options={}){if(!fs35.existsSync(BOOTSTRAP_SKILL_SOURCE))return{status:"error",code:"BUNDLED_SKILL_MISSING",message:`Bundled skill "${BOOTSTRAP_SKILL_NAME}" not found at ${BOOTSTRAP_SKILL_SOURCE}.`,hint:"Try reinstalling fimo, or report this as a bug."};let agents;try{agents=await selectAgents(options,{promptMessage:"Which agents do you want to install to?"})}catch(err){return{status:"error",code:"AGENT_SELECTION_FAILED",message:err instanceof Error?err.message:String(err)}}if(agents.length===0)return{status:"error",code:"NO_AGENTS_SELECTED",message:"`fimo skills install` requires at least one agent.",hint:"Pass --agents=<comma-separated> or run interactively to pick."};let failures=(await installSkillsFromSource({source:BOOTSTRAP_SKILL_SOURCE,agents,global:!0,mode:"symlink"})).failed.map(f=>({agent:f.agent,error:f.error})),removedStale=cleanupStaleGlobalSkills(agents);return{status:"ok",data:{ok:failures.length===0,skill:BOOTSTRAP_SKILL_NAME,agents,failures,removedStale}}}__name(runSkillsInstall,"runSkillsInstall");function renderSkillsInstall(data){let lines=[];if(lines.push(`Installed the ${data.skill} skill globally for: ${data.agents.join(", ")}`),lines.push("Load the version-locked skills on demand: `fimo skills get <name>` (fimo-code, fimo-cli, \u2026)"),data.removedStale.length>0){let names=[...new Set(data.removedStale.map(r=>r.skill))].join(", ");lines.push(`Cleaned up stale global skills from a previous version: ${names}`)}for(let f of data.failures)lines.push(` ! failed for ${f.agent}: ${f.error}`);return lines.join(`
|
|
836
836
|
`)}__name(renderSkillsInstall,"renderSkillsInstall");async function skillsInstallCommand(options={}){let outcome=await runSkillsInstall(options);switch(outcome.status){case"error":ui.error({command:"skills install",code:outcome.code,message:outcome.message,hint:outcome.hint});return;case"cancelled":ui.info({command:"skills install",message:"Cancelled."});return;case"ok":ui.result({command:"skills install",data:outcome.data,render:__name(()=>renderSkillsInstall(outcome.data),"render")});return}}__name(skillsInstallCommand,"skillsInstallCommand");async function skillsSyncCommand(options={}){if(!fs35.existsSync(BOOTSTRAP_SKILL_SOURCE)){ui.error({command:"skills sync",code:"BUNDLED_SKILL_MISSING",message:`Bundled skill "${BOOTSTRAP_SKILL_NAME}" not found in this fimo install.`,hint:"Try reinstalling fimo, or report this as a bug."});return}let explicit;try{explicit=parseAgentsFlag(options)}catch(err){ui.error({command:"skills sync",code:"AGENT_FLAG_PARSE_FAILED",message:err instanceof Error?err.message:String(err)});return}if(explicit==="none"){ui.error({command:"skills sync",code:"INVALID_AGENTS_NONE",message:"`--agents=none` is not valid for sync."});return}let agents=explicit??await detectAgentsWithFimoSkills();if(agents.length===0){ui.result({command:"skills sync",data:{ok:!0,agents:[],failures:[],removedStale:[]},render:__name(()=>"No agents have Fimo skills installed. Run `fimo skills install` first.","render")});return}let failures=(await installSkillsFromSource({source:BOOTSTRAP_SKILL_SOURCE,agents,global:!0,mode:"symlink"})).failed.map(f=>({agent:f.agent,error:f.error})),removedStale=cleanupStaleGlobalSkills(agents);ui.result({command:"skills sync",data:{ok:failures.length===0,agents,failures,removedStale},render:__name(()=>{let lines=[`Re-ensured the ${BOOTSTRAP_SKILL_NAME} skill for: ${agents.join(", ")}`];if(removedStale.length>0){let names=[...new Set(removedStale.map(r=>r.skill))].join(", ");lines.push(`Cleaned up stale global skills: ${names}`)}for(let f of failures)lines.push(` ! failed for ${f.agent}: ${f.error}`);return lines.join(`
|
|
837
837
|
`)},"render")})}__name(skillsSyncCommand,"skillsSyncCommand");async function detectAgentsWithFimoSkills(){let allAgents=getSkillAgentTypes().filter(id=>id!=="universal"),result=[];for(let agent of allAgents){let baseDir;try{baseDir=getSkillAgentDir(agent,{global:!0})}catch{continue}for(let skill of DETECTABLE_FIMO_SKILL_NAMES)if(fs35.existsSync(path35.join(baseDir,skill))){result.push(agent);break}}return result}__name(detectAgentsWithFimoSkills,"detectAgentsWithFimoSkills");function removeDirIfExists(targetPath){return!fs35.existsSync(targetPath)&&!fs35.lstatSync(targetPath,{throwIfNoEntry:!1})?!1:(fs35.rmSync(targetPath,{recursive:!0,force:!0}),!0)}__name(removeDirIfExists,"removeDirIfExists");function removeGlobalSkillDirs(skillNames,agents){let removed=[];for(let agent of agents){let baseDir;try{baseDir=getSkillAgentDir(agent,{global:!0})}catch{continue}for(let skill of skillNames){let skillDir=path35.join(baseDir,skill);removeDirIfExists(skillDir)&&removed.push({skill,agent,path:skillDir})}}return removed}__name(removeGlobalSkillDirs,"removeGlobalSkillDirs");function hasGlobalSkillInstalled(skillNames){for(let agent of getSkillAgentTypes().filter(id=>id!=="universal")){let baseDir;try{baseDir=getSkillAgentDir(agent,{global:!0})}catch{continue}for(let skill of skillNames)if(fs35.existsSync(path35.join(baseDir,skill)))return!0}return!1}__name(hasGlobalSkillInstalled,"hasGlobalSkillInstalled");function removeCanonicalSkillDirs(skillNames){let removed=[],canonicalDir=getCanonicalSkillsDir(!0);for(let skill of skillNames){let canonicalSkill=path35.join(canonicalDir,skill);removeDirIfExists(canonicalSkill)&&removed.push({skill,agent:"canonical",path:canonicalSkill})}return removed}__name(removeCanonicalSkillDirs,"removeCanonicalSkillDirs");function cleanupStaleGlobalSkills(agents){let removed=removeGlobalSkillDirs(STALE_GLOBAL_SKILL_NAMES,agents);return hasGlobalSkillInstalled(STALE_GLOBAL_SKILL_NAMES)||removed.push(...removeCanonicalSkillDirs(STALE_GLOBAL_SKILL_NAMES)),removed}__name(cleanupStaleGlobalSkills,"cleanupStaleGlobalSkills");async function skillsUninstallCommand(options={}){let targetAgents,explicit;try{explicit=parseAgentsFlag(options)}catch(err){ui.error({command:"skills uninstall",code:"AGENT_FLAG_PARSE_FAILED",message:err instanceof Error?err.message:String(err)});return}if(explicit==="none"){ui.error({command:"skills uninstall",code:"INVALID_AGENTS_NONE",message:"`--agents=none` is not valid for uninstall."});return}if(targetAgents=explicit??await detectAgentsWithFimoSkills(),targetAgents.length===0){ui.result({command:"skills uninstall",data:{ok:!0,uninstalled:[]},render:__name(()=>"No Fimo skills are installed for any agent.","render")});return}if(isPrettyMode()&&!!process.stdout.isTTY){mt("Uninstall Fimo skills (global)");let confirmed=await ot2({message:`Remove the Fimo skill from ${targetAgents.join(", ")}?`,initialValue:!0});if(q(confirmed)||!confirmed){ui.info({command:"skills uninstall",message:"Cancelled."});return}}let removed=removeGlobalSkillDirs(DETECTABLE_FIMO_SKILL_NAMES,targetAgents);(await detectAgentsWithFimoSkills()).length===0&&removed.push(...removeCanonicalSkillDirs(DETECTABLE_FIMO_SKILL_NAMES)),ui.result({command:"skills uninstall",data:{ok:!0,uninstalled:removed},render:__name(()=>removed.length===0?"No Fimo skills were installed for the selected agents.":`Uninstalled:
|
|
838
838
|
${removed.map(r=>` ${r.skill} \u2192 ${r.agent}`).join(`
|
|
@@ -840,7 +840,7 @@ ${removed.map(r=>` ${r.skill} \u2192 ${r.agent}`).join(`
|
|
|
840
840
|
`,1)[0]?.trim()??"";return line.length>80?`${line.slice(0,79)}\u2026`:line}__name(firstLine,"firstLine");function skillsListCommand(){let skills2=discoverBundledSkills();if(skills2.length===0){ui.error({command:"skills list",code:"BUNDLED_SKILL_MISSING",message:`No bundled skills found at ${SKILLS_ROOT}.`,hint:"Try reinstalling fimo, or report this as a bug."});return}ui.result({command:"skills list",data:{skills:skills2.map(s=>({name:s.name,description:s.description,refs:s.refs}))},render:__name(()=>{let nameWidth=Math.max(4,...skills2.map(s=>s.name.length)),header=`${"NAME".padEnd(nameWidth)} REFS DESCRIPTION`,lines=skills2.map(s=>{let refs=String(s.refs.length).padStart(4);return`${s.name.padEnd(nameWidth)} ${refs} ${firstLine(s.description)}`});return[header,...lines].join(`
|
|
841
841
|
`)},"render"),hint:"Run `fimo skills get <name>` for a skill, or add `--ref <doc>` for a reference."})}__name(skillsListCommand,"skillsListCommand");function runningCliSource(){let version=getCliVersion();return{status:"ok",data:{root:SKILLS_ROOT,source:"running-cli",version,cliVersion:version}}}__name(runningCliSource,"runningCliSource");function resolveSkillsGetSource(name,cwd){if(name!=="fimo-code")return runningCliSource();let projectRoot=findProjectRoot(cwd);if(!projectRoot)return runningCliSource();let packageJsonPath=resolveProjectFimoPackageJson(projectRoot);if(!packageJsonPath)return{status:"error",code:"PROJECT_RUNTIME_NOT_INSTALLED",message:"The project-local fimo package is not installed, so version-matched code guidance is unavailable.",hint:"Install the project dependencies, then run `fimo skills get fimo-code` again."};let version="unknown";try{let pkg=JSON.parse(fs35.readFileSync(packageJsonPath,"utf8"));typeof pkg.version=="string"&&(version=pkg.version)}catch{}let root=path35.join(path35.dirname(packageJsonPath),"assets","skills");return fs35.existsSync(path35.join(root,"fimo-code","SKILL.md"))?{status:"ok",data:{root,source:"project-runtime",version,cliVersion:getCliVersion()}}:{status:"error",code:"PROJECT_SKILL_UNAVAILABLE",message:`Project runtime fimo@${version} does not include version-matched fimo-code guidance.`,hint:"Upgrade the project runtime, then run `fimo skills get fimo-code` again."}}__name(resolveSkillsGetSource,"resolveSkillsGetSource");function formatSkillStamp(skillName,refId,source,ctx){let separator=ctx.ascii?" | ":" \xB7 ",subject=refId?`${skillName} (references/${refId})`:skillName,origin=source.source==="project-runtime"?[`project runtime fimo@${source.version}`,`CLI fimo@${source.cliVersion}`]:[`running CLI fimo@${source.version}`];return[subject,...origin].join(separator)}__name(formatSkillStamp,"formatSkillStamp");function stampedSkillBody(stamp,content2,ctx){let rule=(ctx.ascii?"-":"\u2500").repeat(stamp.length);return`${stamp}
|
|
842
842
|
${rule}
|
|
843
|
-
${content2}`}__name(stampedSkillBody,"stampedSkillBody");function resolveProjectFimoPackageJson(projectRoot){let requireFromProject=
|
|
843
|
+
${content2}`}__name(stampedSkillBody,"stampedSkillBody");function resolveProjectFimoPackageJson(projectRoot){let requireFromProject=createRequire4(path35.join(projectRoot,"package.json")),ancestorNodeModules=new Set,directory=projectRoot;for(;;){ancestorNodeModules.add(path35.join(directory,"node_modules"));let parent=path35.dirname(directory);if(parent===directory)break;directory=parent}for(let searchRoot of requireFromProject.resolve.paths("fimo")??[]){if(!ancestorNodeModules.has(path35.normalize(searchRoot)))continue;let packageJsonPath=path35.join(searchRoot,"fimo","package.json");if(fs35.existsSync(packageJsonPath))return packageJsonPath}}__name(resolveProjectFimoPackageJson,"resolveProjectFimoPackageJson");function normalizeRef(ref){return ref.trim().replace(/\\/g,"/").replace(/^references\//,"").replace(/\.md$/,"")}__name(normalizeRef,"normalizeRef");function skillsGetCommand(name,options={}){let source=resolveSkillsGetSource(name,path35.resolve(options.cwd??process.cwd()));if(source.status==="error"){ui.error({command:"skills get",code:source.code,message:source.message,hint:source.hint});return}let skills2=discoverBundledSkills(source.data.root),skill=skills2.find(s=>s.name===name);if(!skill){ui.error({command:"skills get",code:"SKILL_NOT_FOUND",message:`Unknown skill "${name}".`,hint:skills2.length?`Available: ${skills2.map(s=>s.name).join(", ")}. Run \`fimo skills list\`.`:"No bundled skills found \u2014 try reinstalling fimo."});return}let targetPath,refId=null;if(options.ref){refId=normalizeRef(options.ref);let refsRoot=path35.resolve(skill.dir,"references"),candidate=path35.resolve(refsRoot,`${refId}.md`);if(!(candidate===refsRoot||candidate.startsWith(refsRoot+path35.sep))||!fs35.existsSync(candidate)){ui.error({command:"skills get",code:"SKILL_REF_NOT_FOUND",message:`Reference "${options.ref}" not found in skill "${skill.name}".`,hint:skill.refs.length?`Available refs: ${skill.refs.join(", ")}.`:"This skill has no reference docs."});return}targetPath=candidate}else targetPath=path35.join(skill.dir,"SKILL.md");let content2=fs35.readFileSync(targetPath,"utf8");ui.result({command:"skills get",data:{skill:skill.name,ref:refId,path:targetPath,content:content2,source:source.data.source,version:source.data.version,cliVersion:source.data.cliVersion},render:__name(ctx=>stampedSkillBody(formatSkillStamp(skill.name,refId,source.data,ctx),content2,ctx),"render"),hint:STREAMED_REFERENCE_HINT})}__name(skillsGetCommand,"skillsGetCommand");var execFileAsync8=promisify9(execFile9),GENERATED_PNPM_PACKAGE_MANAGER="pnpm@10.26.0",ScaffoldError=class extends Error{static{__name(this,"ScaffoldError")}code;hint;constructor(code2,message,hint){super(message),this.name="ScaffoldError",this.code=code2,this.hint=hint}};function explainCreateProjectError(error){return error instanceof ApiRequestError&&error.detail.includes('insert into "projects"')&&(error.detail.includes('"subdomain"')||error.detail.includes('"subdomain_updated_at"'))?["Project creation failed because the local API database schema looks out of date.","The server is trying to write the `projects.subdomain` fields, but your database likely has not applied the latest migration yet.","Run `cd apps/api && pnpm db:migrate`, restart the API if needed, then retry."].join(`
|
|
844
844
|
`):error instanceof Error?error.message:String(error)}__name(explainCreateProjectError,"explainCreateProjectError");async function scaffoldNewProject(args){let{fimo,cfg,targetDir,displayName,options}=args,organizationId=await resolveOrganization(fimo,options.org),createSpinner=spinner("Creating Fimo project"),project;try{({data:project}=await fimo.execute("projects.create",{organizationId,displayName:displayName??path36.basename(targetDir),origin:options.origin}))}catch(error){throw createSpinner.fail("Project creation failed"),new ScaffoldError("PROJECT_CREATE_FAILED",explainCreateProjectError(error))}createSpinner.succeed(`Project ${project.displayName??project.name} created (${project.id})`);let releaseAbort=installAbortHandler(fimo,project.id,project.name);try{return{scaffold:await scaffoldIntoProject({project,cfg,targetDir,options}),releaseAbort}}catch(error){throw releaseAbort(),error}}__name(scaffoldNewProject,"scaffoldNewProject");async function scaffoldIntoProject(args){let{project,cfg,targetDir,options}=args,defaultBranch=project.defaultBranch??DEFAULT_BRANCH,remoteSp=spinner("Fetching git remote"),remote=await createGitService(cfg,defaultBranch).getRemote(project.id,defaultBranch);remoteSp.succeed("Remote ready");let selectedAgents;try{selectedAgents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills})}catch(err){throw new ScaffoldError("AGENT_SELECTION_FAILED",err instanceof Error?err.message:String(err))}let scaffoldSp=spinner("Scaffolding template"),framework=resolveTemplateFramework(options.framework),templateRoot=options.templateRoot?path36.resolve(options.templateRoot):process.env.FIMO_TEMPLATE_ROOT?path36.resolve(process.env.FIMO_TEMPLATE_ROOT):resolveTemplateRoot(framework);await copyTemplate(templateRoot,targetDir),seedSiteName({targetDir,project}),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl});let gitSp=spinner("Initializing git repository");await runGit(["init","-b",defaultBranch],targetDir),await ensureFimoRemote(targetDir,remote.url),gitSp.succeed("Git initialized with `fimo` remote"),scaffoldSp.succeed("Template scaffolded");let relativeTarget=path36.relative(process.cwd(),targetDir)||".";return{project,targetDir,relativeTarget,selectedAgents,tenantApiUrl:remote.tenantApiUrl}}__name(scaffoldIntoProject,"scaffoldIntoProject");async function finalizeInitialCommit(args){let{targetDir}=args,gitSp=spinner("Creating the initial commit");await runGit(["add","-A"],targetDir),await runGit(["commit","-m","chore: scaffold Fimo project"],targetDir).catch(()=>{}),gitSp.succeed("Initial commit created");let pushSp=spinner("Pushing initial commit to Fimo");try{return await runGit(["push","fimo","HEAD"],targetDir),pushSp.succeed("Initial commit pushed"),{pushedInitial:!0}}catch(error){pushSp.fail("Initial push failed");let failure=classifyPushError(error),retryHint=failure.kind==="auth"?"Sign in with `fimo login`, then run `fimo deploy` to push it.":"Run `fimo deploy` later to retry.";return O2.error(`Could not push the initial commit. ${retryHint}
|
|
845
845
|
${failure.stderr||""}`.trim()),{pushedInitial:!1}}}__name(finalizeInitialCommit,"finalizeInitialCommit");function installAbortHandler(fimo,projectId,projectName){let cleaningUp=!1,handler=__name(()=>{cleaningUp&&(process.stderr.write(`
|
|
846
846
|
Force-exiting. Project may not have been fully cleaned up.
|
|
@@ -905,18 +905,18 @@ Examples:
|
|
|
905
905
|
fimo mcp run sentry search_issues --input '{"query":"open regressions"}'
|
|
906
906
|
|
|
907
907
|
Run \`fimo mcp <command> --help\` for command-specific help.
|
|
908
|
-
`);mcp.command("add <name>").description("Add and enable a remote MCP server").requiredOption("--url <https-url>","Remote Streamable HTTP MCP endpoint").option("--auth <mode>","Authentication: auto, none, bearer, or header","auto").option("--header <name>","Private header name (repeat for multiple headers)",collect2).option("--header-name <name>","Header name for --auth header").option("--headers-stdin","Read one JSON object of complete header values from stdin").option("--token <value>","Token or complete header value (prefer --token-stdin in shells that record history)").option("--token-stdin","Read the token or complete header value from stdin").option("--no-open","Print an OAuth URL without opening a browser").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>addMcpCommand(name,opts)),mcp.command("reconnect <server>").description("Authorize an existing OAuth MCP connection again").option("--no-open","Print the authorization URL without opening a browser").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((server,opts)=>reconnectMcpCommand(server,opts)),mcp.command("list").description("List remote MCP servers available to this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listMcpCommand(opts)),mcp.command("search <query>").description("Search the live tools exposed by remote MCP servers").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((query,opts)=>searchMcpCommand(query,opts)),mcp.command("rotate <server>").description("Replace all credentials on an existing remote MCP connection").option("--headers-stdin","Read one JSON object of complete header values from stdin").option("--token-stdin","Read a bearer token from stdin").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((server,opts)=>rotateMcpCommand(server,opts)),mcp.command("info <server>").description("Show one remote MCP server and its live tools").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((server,opts)=>infoCommand(mcpIntegrationKey(server),opts,"mcp info")),mcp.command("run <server> <tool>").description("Run a tool from an enabled remote MCP server").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--input <json|@file|->","Tool input as inline JSON, @file, or - for stdin").action((server,tool,opts)=>runCommand(mcpIntegrationKey(server),tool,{...opts,input:opts.input??"{}"},"mcp run"))}__name(registerMcpCommands,"registerMcpCommands");async function addMcpCommand(name,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),auth=await resolveMcpAuth(opts.auth),credentials=await resolveMcpAddCredentials(auth,opts),result=await integrations.addMcp({projectId,request:{type:"mcp",name,url:opts.url,auth,...credentials}});if(result.mode==="oauth"){opts.open!==!1&&await open_default(result.connectUrl),ui.ok({command:"mcp add",headline:opts.open===!1?`Authorize ${result.integrationKey}`:`Opening ${result.integrationKey} sign in`,details:{project_id:projectId,integration:result.integrationKey,endpoint:result.info.url??opts.url,connect_url:result.connectUrl,expires_at:result.expiresAt}});return}ui.ok({command:"mcp add",headline:`Added ${result.integrationKey}`,details:{project_id:projectId,integration:result.integrationKey,endpoint:result.info.url??opts.url,auth,tools:result.info.tools.map(tool=>tool.key).join(", ")||"none"}})}__name(addMcpCommand,"addMcpCommand");async function reconnectMcpCommand(server,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),integrationKey=mcpIntegrationKey(server),result=await integrations.connect({projectId,integrationKey,request:{mode:"oauth",reconnect:!0}});if(result.mode!=="oauth")throw new Error(`MCP server '${server}' did not return an OAuth authorization URL.`);opts.open!==!1&&await open_default(result.connectUrl),ui.ok({command:"mcp reconnect",headline:opts.open===!1?`Reconnect ${integrationKey}`:`Opening ${integrationKey} sign in`,details:{project_id:projectId,integration:integrationKey,connect_url:result.connectUrl,expires_at:result.expiresAt}})}__name(reconnectMcpCommand,"reconnectMcpCommand");async function rotateMcpCommand(server,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),integrationKey=mcpIntegrationKey(server),[info,status]=await Promise.all([integrations.getInfo(projectId,integrationKey),integrations.getStatus(projectId,integrationKey)]);if(!status.connectionAlias)throw new Error(`MCP server '${server}' does not have an active connection to rotate.`);if(info.credentials.length===0)throw new Error(`MCP server '${server}' does not require credentials.`);let bearer=info.credentials.length===1&&info.credentials[0]?.usage==="http_bearer";if(bearer&&!opts.tokenStdin)throw new Error("Pipe the replacement bearer token with --token-stdin.");if(bearer&&opts.headersStdin)throw new Error("Bearer MCP servers use --token-stdin, not --headers-stdin.");if(!bearer&&!opts.headersStdin)throw new Error("Pipe the complete replacement header bundle with --headers-stdin.");if(!bearer&&opts.tokenStdin)throw new Error("Custom-header MCP servers use --headers-stdin, not --token-stdin.");let request=bearer?{mode:"personal",alias:status.connectionAlias,token:await readStdinValue3("token"),rotate:!0}:{mode:"personal",alias:status.connectionAlias,secrets:await readHeaderSecrets(info.credentials.map(credential=>({name:credential.id}))),rotate:!0},result=await integrations.connect({projectId,integrationKey,request});if(result.mode!=="personal")throw new Error(`MCP server '${server}' did not return a personal connection.`);ui.ok({command:"mcp rotate",headline:`Rotated ${integrationKey}`,details:{project_id:projectId,integration:integrationKey,connection:result.connection.alias,credentials:bearer?"bearer token":info.credentials.map(credential=>credential.label).join(", ")}})}__name(rotateMcpCommand,"rotateMcpCommand");async function listMcpCommand(opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),rows=(await integrations.list(projectId)).filter(isMcpIntegration).map(toMcpListRow);ui.table({command:"mcp list",columns:[{key:"server",label:"SERVER"},{key:"integration",label:"INTEGRATION"},{key:"status",label:"STATUS"},{key:"auth",label:"AUTH"},{key:"connection",label:"CONNECTION"}],rows})}__name(listMcpCommand,"listMcpCommand");async function searchMcpCommand(query,opts){let normalizedQuery=query.trim().toLowerCase();if(!normalizedQuery)throw new Error("Search query cannot be empty.");let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),statuses=(await integrations.list(projectId)).filter(isMcpIntegration),catalogs=await Promise.all(statuses.map(async status=>({status,info:await integrations.getInfo(projectId,status.integrationKey)}))),rows=[];for(let{status,info}of catalogs){let serverMatches=[status.integrationKey,status.name,status.summary,info.url].filter(value=>!!value).some(value=>value.toLowerCase().includes(normalizedQuery));for(let tool of info.tools){let toolMatches=[tool.key,tool.name,tool.description].some(value=>value.toLowerCase().includes(normalizedQuery));!serverMatches&&!toolMatches||rows.push({integration:status.integrationKey,tool:tool.key,effect:tool.effect,description:tool.description})}}ui.table({command:"mcp search",columns:[{key:"integration",label:"INTEGRATION"},{key:"tool",label:"TOOL"},{key:"effect",label:"EFFECT"},{key:"description",label:"DESCRIPTION"}],rows})}__name(searchMcpCommand,"searchMcpCommand");function isMcpIntegration(status){return status.integrationKey.startsWith("mcp_")}__name(isMcpIntegration,"isMcpIntegration");function toMcpListRow(status){return{server:status.name,integration:status.integrationKey,status:status.enabled?"enabled":status.installed?"disabled":"available",auth:status.authModeLabel??"",connection:status.connectionAlias??""}}__name(toMcpListRow,"toMcpListRow");function mcpIntegrationKey(server){let value=server.trim();if(!value)throw new Error("MCP server name cannot be empty.");if(value.startsWith("mcp_"))return value;let slug=value.normalize("NFKD").toLowerCase().replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,116);if(!slug)throw new Error("MCP server name must contain a letter or number.");return`mcp_${slug}`}__name(mcpIntegrationKey,"mcpIntegrationKey");function resolveProjectId6(opts){return opts.project?opts.project:loadProjectSettings(resolveProjectCwd(opts.cwd)).projectId}__name(resolveProjectId6,"resolveProjectId");async function resolveMcpAuth(value){if(value){let normalized=value.trim().toLowerCase();if(normalized==="auto"||normalized==="none"||normalized==="bearer"||normalized==="header")return normalized;throw new Error("--auth must be auto, none, bearer, or header.")}return"auto"}__name(resolveMcpAuth,"resolveMcpAuth");async function resolveMcpAddCredentials(auth,opts){let hasHeaderOptions=!!(opts.header?.length||opts.headerName),hasTokenOptions=!!(opts.token||opts.tokenStdin);if(opts.headersStdin&&hasTokenOptions)throw new Error("Use either --headers-stdin or a single token option, not both.");if(auth==="auto"||auth==="none"){if(hasHeaderOptions||hasTokenOptions||opts.headersStdin)throw new Error(`--auth ${auth} does not accept header or token options.`);return{}}if(auth==="bearer"){if(hasHeaderOptions||opts.headersStdin)throw new Error("--auth bearer does not accept custom header options.");return{token:await resolveMcpToken(opts,"MCP token")}}let headers=await resolveMcpHeaders(opts);if(opts.headersStdin)return{headers,secrets:await readHeaderSecrets(headers)};if(headers.length!==1)throw new Error("Multiple custom headers require a complete JSON object piped with --headers-stdin.");let name=headers[0].name;return{headers,secrets:{[name.toLowerCase()]:await resolveMcpToken(opts,`Complete ${name} value`)}}}__name(resolveMcpAddCredentials,"resolveMcpAddCredentials");async function resolveMcpHeaders(opts){if(opts.header?.length&&opts.headerName)throw new Error("Use repeated --header options or --header-name, not both.");let names=opts.header?.length?opts.header:[await resolveMcpHeaderName(opts.headerName)],normalized=new Set;return names.map(name=>{let value=name.trim();if(!value||value.length>120||!MCP_HEADER_NAME.test(value))throw new Error(`Invalid MCP header name '${value||"(empty)"}'.`);let key=value.toLowerCase();if(normalized.has(key))throw new Error(`MCP header '${value}' is configured more than once.`);return normalized.add(key),{name:value}})}__name(resolveMcpHeaders,"resolveMcpHeaders");async function readHeaderSecrets(headers){let raw=await readStdinValue3("header JSON"),parsed;try{parsed=JSON.parse(raw)}catch{throw new Error("--headers-stdin expects one JSON object of header names to complete header values.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("--headers-stdin expects one JSON object of header names to complete header values.");let provided=new Map;for(let[name,secret]of Object.entries(parsed)){let key=name.trim().toLowerCase();if(provided.has(key))throw new Error(`Header '${name}' appears more than once when compared case-insensitively.`);if(typeof secret!="string"||secret.length===0)throw new Error(`Header '${name}' needs a non-empty string value.`);provided.set(key,secret)}let expected=new Map(headers.map(header=>[header.name.toLowerCase(),header.name])),missing=[...expected].filter(([key])=>!provided.has(key)).map(([,name])=>name),extra=[...provided.keys()].filter(key=>!expected.has(key));if(missing.length>0||extra.length>0){let details=[missing.length>0?`missing: ${missing.join(", ")}`:"",extra.length>0?`unexpected: ${extra.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Header credentials must exactly match the configured headers (${details}).`)}return Object.fromEntries([...expected.keys()].map(key=>[key,provided.get(key)]))}__name(readHeaderSecrets,"readHeaderSecrets");async function resolveMcpHeaderName(value){if(value?.trim())return value.trim();assertInteractive("Pass --header-name <name> with --auth header.","mcp add");let selected=await Ot({message:"Authentication header name",placeholder:"X-API-Key",validate:__name(input=>input?.trim().length?void 0:"header name required","validate")});if(q(selected))throw new Error("Cancelled.");return String(selected).trim()}__name(resolveMcpHeaderName,"resolveMcpHeaderName");async function resolveMcpToken(opts,message){if(opts.token)return opts.token;if(opts.tokenStdin)return readStdinValue3("token");assertInteractive("Pass --token-stdin or --token <value>.","mcp add");let value=await bt({message,validate:__name(input=>input?.trim().length?void 0:"value required","validate")});if(q(value))throw new Error("Cancelled.");return String(value)}__name(resolveMcpToken,"resolveMcpToken");async function readStdinValue3(kind){if(process.stdin.isTTY)throw new Error(`Pipe the ${kind} to the command.`);let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let value=Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"");if(!value)throw new Error(`The piped ${kind} cannot be empty.`);return value}__name(readStdinValue3,"readStdinValue");function collect2(value,previous){return[...previous??[],value]}__name(collect2,"collect");init_esm();init_dist();init_project_context();function taskTokens(task){let argv=process.argv.slice(2),namespaceIndex=argv.indexOf(task.modality);if(namespaceIndex===-1)return[];let verbIndex=argv.indexOf(task.operation,namespaceIndex+1);return verbIndex===-1?[]:argv.slice(verbIndex+1)}__name(taskTokens,"taskTokens");function renderTaskHelp(task){return renderGenerationHelp({usage:`fimo ${task.modality} ${task.operation} [flags]`,description:task.description,flags:task.flags})}__name(renderTaskHelp,"renderTaskHelp");async function runTask(task,command){let tokens=taskTokens(task),wantsHelp=tokens.includes("--help")||tokens.includes("-h"),commandName2=`${task.modality} ${task.operation}`;if(wantsHelp){ui.result({command:commandName2,data:{task},render:__name(()=>renderTaskHelp(task),"render")});return}let{values,bools,options}=parseGenerationFlags({commandName:commandName2,subject:task.id,helpCommand:`fimo ${commandName2} --help`,flags:task.flags,tokens}),body={task:task.id,options,name:values.get("name")?.[0],parentId:values.get("parent")?.[0]??null},isJson=currentMode().format==="json",{ctx,fimo}=await bootstrapProjectCommand({cwd:values.get("cwd")?.[0]},command,{refuseReadOnly:!0,quiet:isJson});if(bools.get("dry-run")===!0){let estimate=await fimo.execute("generation.estimateTask",{projectId:ctx.projectId,branch:ctx.branch,task:task.id,options}),data={...body,estimate};ui.result({command:commandName2,data,render:__name(()=>JSON.stringify(data,null,2),"render")});return}await submitGeneration({commandName:commandName2,ctx,fimo,body})}__name(runTask,"runTask");function registerTaskCommand(parent,task){parent.command(task.operation).description(task.description).allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(_options,command)=>{await runTask(task,command)})}__name(registerTaskCommand,"registerTaskCommand");function registerMediaTaskCommands(program2){let image=program2.command("image").description("Generate and transform images"),video=program2.command("video").description("Generate and transform videos");for(let task of GENERATION_TASK_MANIFESTS)registerTaskCommand(task.modality==="image"?image:video,task)}__name(registerMediaTaskCommands,"registerMediaTaskCommands");import{execSync,spawnSync as spawnSync3}from"node:child_process";import{mkdtempSync,readFileSync as readFileSync10,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path43 from"node:path";init_dist();init_config();init_sdk_transport();init_color();function renderMergeSuccess(result,p2){let lines=[];if(lines.push(p2.green(`\u2713 Merged ${result.fromBranch??result.fromEnv} \u2192 ${result.toBranch??result.toEnv}`)),result.summary&&lines.push(p2.dim(` ${result.summary}`)),result.applied.length>0){lines.push(""),lines.push(p2.bold("Applied:"));for(let a of result.applied)lines.push(p2.dim(` ${a.surface.padEnd(14)} ${a.count} item${a.count===1?"":"s"}`))}return lines.join(`
|
|
908
|
+
`);mcp.command("add <name>").description("Add and enable a remote MCP server").requiredOption("--url <https-url>","Remote Streamable HTTP MCP endpoint").option("--auth <mode>","Authentication: auto, none, bearer, or header","auto").option("--header <name>","Private header name (repeat for multiple headers)",collect2).option("--header-name <name>","Header name for --auth header").option("--headers-stdin","Read one JSON object of complete header values from stdin").option("--token <value>","Token or complete header value (prefer --token-stdin in shells that record history)").option("--token-stdin","Read the token or complete header value from stdin").option("--no-open","Print an OAuth URL without opening a browser").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>addMcpCommand(name,opts)),mcp.command("reconnect <server>").description("Authorize an existing OAuth MCP connection again").option("--no-open","Print the authorization URL without opening a browser").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((server,opts)=>reconnectMcpCommand(server,opts)),mcp.command("list").description("List remote MCP servers available to this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listMcpCommand(opts)),mcp.command("search <query>").description("Search the live tools exposed by remote MCP servers").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((query,opts)=>searchMcpCommand(query,opts)),mcp.command("rotate <server>").description("Replace all credentials on an existing remote MCP connection").option("--headers-stdin","Read one JSON object of complete header values from stdin").option("--token-stdin","Read a bearer token from stdin").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((server,opts)=>rotateMcpCommand(server,opts)),mcp.command("info <server>").description("Show one remote MCP server and its live tools").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((server,opts)=>infoCommand(mcpIntegrationKey(server),opts,"mcp info")),mcp.command("run <server> <tool>").description("Run a tool from an enabled remote MCP server").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--input <json|@file|->","Tool input as inline JSON, @file, or - for stdin").action((server,tool,opts)=>runCommand(mcpIntegrationKey(server),tool,{...opts,input:opts.input??"{}"},"mcp run"))}__name(registerMcpCommands,"registerMcpCommands");async function addMcpCommand(name,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),auth=await resolveMcpAuth(opts.auth),credentials=await resolveMcpAddCredentials(auth,opts),result=await integrations.addMcp({projectId,request:{type:"mcp",name,url:opts.url,auth,...credentials}});if(result.mode==="oauth"){opts.open!==!1&&await open_default(result.connectUrl),ui.ok({command:"mcp add",headline:opts.open===!1?`Authorize ${result.integrationKey}`:`Opening ${result.integrationKey} sign in`,details:{project_id:projectId,integration:result.integrationKey,endpoint:result.info.url??opts.url,connect_url:result.connectUrl,expires_at:result.expiresAt}});return}ui.ok({command:"mcp add",headline:`Added ${result.integrationKey}`,details:{project_id:projectId,integration:result.integrationKey,endpoint:result.info.url??opts.url,auth,tools:result.info.tools.map(tool=>tool.key).join(", ")||"none"}})}__name(addMcpCommand,"addMcpCommand");async function reconnectMcpCommand(server,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),integrationKey=mcpIntegrationKey(server),result=await integrations.connect({projectId,integrationKey,request:{mode:"oauth",reconnect:!0}});if(result.mode!=="oauth")throw new Error(`MCP server '${server}' did not return an OAuth authorization URL.`);opts.open!==!1&&await open_default(result.connectUrl),ui.ok({command:"mcp reconnect",headline:opts.open===!1?`Reconnect ${integrationKey}`:`Opening ${integrationKey} sign in`,details:{project_id:projectId,integration:integrationKey,connect_url:result.connectUrl,expires_at:result.expiresAt}})}__name(reconnectMcpCommand,"reconnectMcpCommand");async function rotateMcpCommand(server,opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),integrationKey=mcpIntegrationKey(server),[info,status]=await Promise.all([integrations.getInfo(projectId,integrationKey),integrations.getStatus(projectId,integrationKey)]);if(!status.connectionAlias)throw new Error(`MCP server '${server}' does not have an active connection to rotate.`);if(info.credentials.length===0)throw new Error(`MCP server '${server}' does not require credentials.`);let bearer=info.credentials.length===1&&info.credentials[0]?.usage==="http_bearer";if(bearer&&!opts.tokenStdin)throw new Error("Pipe the replacement bearer token with --token-stdin.");if(bearer&&opts.headersStdin)throw new Error("Bearer MCP servers use --token-stdin, not --headers-stdin.");if(!bearer&&!opts.headersStdin)throw new Error("Pipe the complete replacement header bundle with --headers-stdin.");if(!bearer&&opts.tokenStdin)throw new Error("Custom-header MCP servers use --headers-stdin, not --token-stdin.");let request=bearer?{mode:"personal",alias:status.connectionAlias,token:await readStdinValue3("token"),rotate:!0}:{mode:"personal",alias:status.connectionAlias,secrets:await readHeaderSecrets(info.credentials.map(credential=>({name:credential.id}))),rotate:!0},result=await integrations.connect({projectId,integrationKey,request});if(result.mode!=="personal")throw new Error(`MCP server '${server}' did not return a personal connection.`);ui.ok({command:"mcp rotate",headline:`Rotated ${integrationKey}`,details:{project_id:projectId,integration:integrationKey,connection:result.connection.alias,credentials:bearer?"bearer token":info.credentials.map(credential=>credential.label).join(", ")}})}__name(rotateMcpCommand,"rotateMcpCommand");async function listMcpCommand(opts){let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),rows=(await integrations.list(projectId)).filter(isMcpIntegration).map(toMcpListRow);ui.table({command:"mcp list",columns:[{key:"server",label:"SERVER"},{key:"integration",label:"INTEGRATION"},{key:"status",label:"STATUS"},{key:"auth",label:"AUTH"},{key:"connection",label:"CONNECTION"}],rows})}__name(listMcpCommand,"listMcpCommand");async function searchMcpCommand(query,opts){let normalizedQuery=query.trim().toLowerCase();if(!normalizedQuery)throw new Error("Search query cannot be empty.");let integrations=createIntegrationService(loadConfig()),projectId=resolveProjectId6(opts),statuses=(await integrations.list(projectId)).filter(isMcpIntegration),catalogs=await Promise.all(statuses.map(async status=>({status,info:await integrations.getInfo(projectId,status.integrationKey)}))),rows=[];for(let{status,info}of catalogs){let serverMatches=[status.integrationKey,status.name,status.summary,info.url].filter(value=>!!value).some(value=>value.toLowerCase().includes(normalizedQuery));for(let tool of info.tools){let toolMatches=[tool.key,tool.name,tool.description].some(value=>value.toLowerCase().includes(normalizedQuery));!serverMatches&&!toolMatches||rows.push({integration:status.integrationKey,tool:tool.key,effect:tool.effect,description:tool.description})}}ui.table({command:"mcp search",columns:[{key:"integration",label:"INTEGRATION"},{key:"tool",label:"TOOL"},{key:"effect",label:"EFFECT"},{key:"description",label:"DESCRIPTION"}],rows})}__name(searchMcpCommand,"searchMcpCommand");function isMcpIntegration(status){return status.integrationKey.startsWith("mcp_")}__name(isMcpIntegration,"isMcpIntegration");function toMcpListRow(status){return{server:status.name,integration:status.integrationKey,status:status.enabled?"enabled":status.installed?"disabled":"available",auth:status.authModeLabel??"",connection:status.connectionAlias??""}}__name(toMcpListRow,"toMcpListRow");function mcpIntegrationKey(server){let value=server.trim();if(!value)throw new Error("MCP server name cannot be empty.");if(value.startsWith("mcp_"))return value;let slug=value.normalize("NFKD").toLowerCase().replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,116);if(!slug)throw new Error("MCP server name must contain a letter or number.");return`mcp_${slug}`}__name(mcpIntegrationKey,"mcpIntegrationKey");function resolveProjectId6(opts){return opts.project?opts.project:loadProjectSettings(resolveProjectCwd(opts.cwd)).projectId}__name(resolveProjectId6,"resolveProjectId");async function resolveMcpAuth(value){if(value){let normalized=value.trim().toLowerCase();if(normalized==="auto"||normalized==="none"||normalized==="bearer"||normalized==="header")return normalized;throw new Error("--auth must be auto, none, bearer, or header.")}return"auto"}__name(resolveMcpAuth,"resolveMcpAuth");async function resolveMcpAddCredentials(auth,opts){let hasHeaderOptions=!!(opts.header?.length||opts.headerName),hasTokenOptions=!!(opts.token||opts.tokenStdin);if(opts.headersStdin&&hasTokenOptions)throw new Error("Use either --headers-stdin or a single token option, not both.");if(auth==="auto"||auth==="none"){if(hasHeaderOptions||hasTokenOptions||opts.headersStdin)throw new Error(`--auth ${auth} does not accept header or token options.`);return{}}if(auth==="bearer"){if(hasHeaderOptions||opts.headersStdin)throw new Error("--auth bearer does not accept custom header options.");return{token:await resolveMcpToken(opts,"MCP token")}}let headers=await resolveMcpHeaders(opts);if(opts.headersStdin)return{headers,secrets:await readHeaderSecrets(headers)};if(headers.length!==1)throw new Error("Multiple custom headers require a complete JSON object piped with --headers-stdin.");let name=headers[0].name;return{headers,secrets:{[name.toLowerCase()]:await resolveMcpToken(opts,`Complete ${name} value`)}}}__name(resolveMcpAddCredentials,"resolveMcpAddCredentials");async function resolveMcpHeaders(opts){if(opts.header?.length&&opts.headerName)throw new Error("Use repeated --header options or --header-name, not both.");let names=opts.header?.length?opts.header:[await resolveMcpHeaderName(opts.headerName)],normalized=new Set;return names.map(name=>{let value=name.trim();if(!value||value.length>120||!MCP_HEADER_NAME.test(value))throw new Error(`Invalid MCP header name '${value||"(empty)"}'.`);let key=value.toLowerCase();if(normalized.has(key))throw new Error(`MCP header '${value}' is configured more than once.`);return normalized.add(key),{name:value}})}__name(resolveMcpHeaders,"resolveMcpHeaders");async function readHeaderSecrets(headers){let raw=await readStdinValue3("header JSON"),parsed;try{parsed=JSON.parse(raw)}catch{throw new Error("--headers-stdin expects one JSON object of header names to complete header values.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("--headers-stdin expects one JSON object of header names to complete header values.");let provided=new Map;for(let[name,secret]of Object.entries(parsed)){let key=name.trim().toLowerCase();if(provided.has(key))throw new Error(`Header '${name}' appears more than once when compared case-insensitively.`);if(typeof secret!="string"||secret.length===0)throw new Error(`Header '${name}' needs a non-empty string value.`);provided.set(key,secret)}let expected=new Map(headers.map(header=>[header.name.toLowerCase(),header.name])),missing=[...expected].filter(([key])=>!provided.has(key)).map(([,name])=>name),extra=[...provided.keys()].filter(key=>!expected.has(key));if(missing.length>0||extra.length>0){let details=[missing.length>0?`missing: ${missing.join(", ")}`:"",extra.length>0?`unexpected: ${extra.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Header credentials must exactly match the configured headers (${details}).`)}return Object.fromEntries([...expected.keys()].map(key=>[key,provided.get(key)]))}__name(readHeaderSecrets,"readHeaderSecrets");async function resolveMcpHeaderName(value){if(value?.trim())return value.trim();assertInteractive("Pass --header-name <name> with --auth header.","mcp add");let selected=await Ot({message:"Authentication header name",placeholder:"X-API-Key",validate:__name(input=>input?.trim().length?void 0:"header name required","validate")});if(q(selected))throw new Error("Cancelled.");return String(selected).trim()}__name(resolveMcpHeaderName,"resolveMcpHeaderName");async function resolveMcpToken(opts,message){if(opts.token)return opts.token;if(opts.tokenStdin)return readStdinValue3("token");assertInteractive("Pass --token-stdin or --token <value>.","mcp add");let value=await bt({message,validate:__name(input=>input?.trim().length?void 0:"value required","validate")});if(q(value))throw new Error("Cancelled.");return String(value)}__name(resolveMcpToken,"resolveMcpToken");async function readStdinValue3(kind){if(process.stdin.isTTY)throw new Error(`Pipe the ${kind} to the command.`);let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));let value=Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"");if(!value)throw new Error(`The piped ${kind} cannot be empty.`);return value}__name(readStdinValue3,"readStdinValue");function collect2(value,previous){return[...previous??[],value]}__name(collect2,"collect");init_esm();init_dist();init_project_context();function taskTokens(task){let argv=process.argv.slice(2),namespaceIndex=argv.indexOf(task.modality);if(namespaceIndex===-1)return[];let verbIndex=argv.indexOf(task.operation,namespaceIndex+1);return verbIndex===-1?[]:argv.slice(verbIndex+1)}__name(taskTokens,"taskTokens");function renderTaskHelp(task){return renderGenerationHelp({usage:`fimo ${task.modality} ${task.operation} [flags]`,description:task.description,flags:task.flags})}__name(renderTaskHelp,"renderTaskHelp");async function runTask(task,command){let tokens=taskTokens(task),wantsHelp=tokens.includes("--help")||tokens.includes("-h"),commandName2=`${task.modality} ${task.operation}`;if(wantsHelp){ui.result({command:commandName2,data:{task},render:__name(()=>renderTaskHelp(task),"render")});return}let{values,bools,options}=parseGenerationFlags({commandName:commandName2,subject:task.id,helpCommand:`fimo ${commandName2} --help`,flags:task.flags,tokens}),body={task:task.id,options,name:values.get("name")?.[0],parentId:values.get("parent")?.[0]??null},isJson=currentMode().format==="json",{ctx,fimo}=await bootstrapProjectCommand({cwd:values.get("cwd")?.[0]},command,{refuseReadOnly:!0,quiet:isJson});if(bools.get("dry-run")===!0){let estimate=await fimo.execute("generation.estimateTask",{projectId:ctx.projectId,branch:ctx.branch,task:task.id,options}),data={...body,estimate};ui.result({command:commandName2,data,render:__name(()=>JSON.stringify(data,null,2),"render")});return}await submitGeneration({commandName:commandName2,ctx,fimo,body})}__name(runTask,"runTask");function registerTaskCommand(parent,task){parent.command(task.operation).description(task.description).allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(_options,command)=>{await runTask(task,command)})}__name(registerTaskCommand,"registerTaskCommand");function registerMediaTaskCommands(program2){let image=program2.command("image").description("Generate and transform images"),video=program2.command("video").description("Generate and transform videos");for(let task of GENERATION_TASK_MANIFESTS)registerTaskCommand(task.modality==="image"?image:video,task)}__name(registerMediaTaskCommands,"registerMediaTaskCommands");import{execSync,spawnSync as spawnSync3}from"node:child_process";import{mkdtempSync,readFileSync as readFileSync11,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path43 from"node:path";init_dist();init_config();init_sdk_transport();init_color();function renderMergeSuccess(result,p2){let lines=[];if(lines.push(p2.green(`\u2713 Merged ${result.fromBranch??result.fromEnv} \u2192 ${result.toBranch??result.toEnv}`)),result.summary&&lines.push(p2.dim(` ${result.summary}`)),result.applied.length>0){lines.push(""),lines.push(p2.bold("Applied:"));for(let a of result.applied)lines.push(p2.dim(` ${a.surface.padEnd(14)} ${a.count} item${a.count===1?"":"s"}`))}return lines.join(`
|
|
909
909
|
`)}__name(renderMergeSuccess,"renderMergeSuccess");function renderConflict(conflict,p2){let lines=[];return lines.push(`${p2.yellow("!")} ${p2.bold(`${conflict.surface}: ${conflict.key}`)}`),lines.push(p2.dim(` ${conflict.description}`)),conflict.parentValue!==void 0&&lines.push(p2.dim(" parent: ")+summariseValue(conflict.parentValue)),conflict.childValue!==void 0&&lines.push(p2.dim(" child: ")+summariseValue(conflict.childValue)),lines.join(`
|
|
910
910
|
`)}__name(renderConflict,"renderConflict");function renderResolverHeader(conflicts,p2){let surfaceCounts=conflicts.reduce((acc,c2)=>(acc[c2.surface]=(acc[c2.surface]??0)+1,acc),{}),parts=Object.entries(surfaceCounts).map(([s,n])=>`${n} ${s}`);return p2.yellow(`! ${conflicts.length} conflict${conflicts.length===1?"":"s"} (${parts.join(", ")}) \u2014 resolve below.`)}__name(renderResolverHeader,"renderResolverHeader");function summariseValue(v){if(v===null)return"null";if(typeof v=="string")return v.length>60?v.slice(0,57)+"...":v;if(typeof v=="number"||typeof v=="boolean")return String(v);try{let s=JSON.stringify(v);return s.length>60?s.slice(0,57)+"...":s}catch{return"[unserialisable]"}}__name(summariseValue,"summariseValue");init_project_context();init_esm();var ProtectedFlowError=class extends Error{static{__name(this,"ProtectedFlowError")}env;constructor(env){super(`Refusing to run this mutating command against the protected Branch '${env}'. Use the PR/review flow or pass --allow-direct-merge to override.`),this.name="ProtectedFlowError",this.env=env}};function assertNotOnMain(env,opts={}){let protectedEnvs=opts.protectedEnvs??[DEFAULT_BRANCH];if(!opts.allowDirectMerge&&protectedEnvs.includes(env))throw new ProtectedFlowError(env)}__name(assertNotOnMain,"assertNotOnMain");async function fetchDrillContext(args){let{fimo,ctx,fromBranch,conflict,p:p2}=args,surface=conflict.surface;try{switch(surface){case"code":{let payload=await fimo.execute("branches.diffCodeFile",{projectId:ctx.projectId,branch:fromBranch,path:conflict.key,against:ctx.branch});return renderCodeFileDiff(payload,p2,{bare:!1})}case"content":{let[collection,rowId]=splitOnce2(conflict.key,":");if(!collection||!rowId)return null;let payload=await fimo.execute("branches.diffContentEntry",{projectId:ctx.projectId,branch:fromBranch,collection,rowId,against:ctx.branch});return renderContentRowDiff(payload,p2,{bare:!1})}case"translations":{let[locale,key]=splitOnce2(conflict.key,":");if(!locale||!key)return null;let payload=await fimo.execute("branches.diffLabel",{projectId:ctx.projectId,branch:fromBranch,locale,key,against:ctx.branch});return renderTranslationRowDiff(payload,p2,{bare:!1})}case"schemas":{let payload=await fimo.execute("branches.diffSchema",{projectId:ctx.projectId,branch:fromBranch,typeName:conflict.key,against:ctx.branch});return renderSchemaTypeDiff(payload,p2,{bare:!1})}case"forms":{let payload=await fimo.execute("branches.diffForm",{projectId:ctx.projectId,branch:fromBranch,formName:conflict.key,against:ctx.branch});return renderFormSchemaDiff(payload,p2,{bare:!1})}case"assets":{let payload=await fimo.execute("branches.diffAsset",{projectId:ctx.projectId,branch:fromBranch,assetId:conflict.key,against:ctx.branch});return renderAssetDiff(payload,p2,{bare:!1})}}}catch{return null}return null}__name(fetchDrillContext,"fetchDrillContext");function splitOnce2(s,sep2){let idx=s.indexOf(sep2);return idx<0?[s,""]:[s.slice(0,idx),s.slice(idx+1)]}__name(splitOnce2,"splitOnce");function portableResolution(resolution){return{...resolution,surface:resolution.surface==="translations"?"labels":resolution.surface}}__name(portableResolution,"portableResolution");function legacyConflict(conflict){return{...conflict,surface:conflict.surface==="labels"?"translations":conflict.surface}}__name(legacyConflict,"legacyConflict");function legacyMergeResult(result){return{...result,fromEnv:result.fromBranch,toEnv:result.toBranch,applied:result.applied.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),conflicts:result.conflicts?.map(legacyConflict)}}__name(legacyMergeResult,"legacyMergeResult");var DRAFT_DEBOUNCE_MS=1500;async function mergeCommand(from,options,cmd){let program2=cmd?.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch);try{assertNotOnMain(ctx.branch,{allowDirectMerge:options.allowDirectMerge})}catch(err){if(err instanceof ProtectedFlowError){ui.error({command:"merge",code:"PROTECTED_FLOW",message:err.message,hint:"See: https://fimo.ai/docs/environments/overview#a-pr-style-flow"});return}throw err}let isJson=currentMode().format==="json",p2=options.noColor?makeColorPalette({forceDisable:!0}):palette;if(options.resume){if(isJson){ui.error({command:"merge",code:"NON_INTERACTIVE_REFUSAL",message:"--resume requires interactive mode"});return}return resumeMerge({fimo,ctx,from,options,p:p2})}isJson||mt(p2.bold(`Merging ${from} \u2192 ${ctx.branch}`));let result;try{result=legacyMergeResult(await fimo.execute("branches.merge",{projectId:ctx.projectId,branch:ctx.branch,from,allowDirectMerge:options.allowDirectMerge}))}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_REQUEST_FAILED",message:`Merge failed: ${err.message}`});return}if(result.ok){ui.result({command:"merge",data:result,render:__name(rctx=>renderMergeSuccess(result,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}let conflicts=result.conflicts??[];if(conflicts.length===0){ui.error({command:"merge",code:"MERGE_EMPTY_CONFLICTS",message:"Merge returned ok=false but produced no conflicts. Aborting."});return}if(isJson){ui.result({command:"merge",data:result,render:__name(()=>"","render")});return}O2.warn(renderResolverHeader(conflicts,p2));let resolutions=await resolveConflictsInteractive({fimo,ctx,from,mergeId:result.mergeId,conflicts,drafted:[],p:p2,acceptDefaults:options.yes===!0});if(resolutions===null){await fimo.execute("branches.cancelMerge",{projectId:ctx.projectId,branch:ctx.branch,mergeId:result.mergeId}).catch(()=>{}),ui.error({command:"merge",code:"MERGE_CANCELLED",message:"Merge cancelled; compensating actions triggered server-side."});return}await commitResolutions({fimo,ctx,from,mergeId:result.mergeId,resolutions})}__name(mergeCommand,"mergeCommand");async function resolveConflictsInteractive(args){let draftedMap=new Map;for(let d3 of args.drafted)draftedMap.set(`${d3.surface}:${d3.key}`,d3);let resolutions=[...args.drafted],pendingSave=null,flush=__name(async()=>{pendingSave&&(clearTimeout(pendingSave),pendingSave=null);try{await args.fimo.execute("branches.saveMergeDraft",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from,mergeId:args.mergeId,resolutions:resolutions.map(portableResolution)})}catch{}},"flush"),scheduleSave=__name(()=>{pendingSave&&clearTimeout(pendingSave),pendingSave=setTimeout(()=>{flush().catch(()=>{})},DRAFT_DEBOUNCE_MS)},"scheduleSave");for(let conflict of args.conflicts){let key=`${conflict.surface}:${conflict.key}`;if(draftedMap.has(key))continue;if(await printConflictWithContext(args.fimo,args.ctx,args.from,conflict,args.p),args.acceptDefaults){resolutions.push({surface:conflict.surface,key:conflict.key,choice:"parent"}),scheduleSave();continue}let isCode=conflict.surface==="code",choice=await _t({message:"How should this conflict be resolved?",options:[{value:"parent",label:isCode?`parent \u2014 keep ${args.ctx.branch}'s file`:"parent \u2014 keep target value"},{value:"child",label:isCode?`child \u2014 take ${args.from}'s file`:"child \u2014 take source value"},{value:"pick",label:isCode?"pick \u2014 resolve conflict markers in $EDITOR":"pick \u2014 edit a custom value in $EDITOR"},{value:"abort",label:"abort \u2014 cancel the merge"}]});if(q(choice)||choice==="abort")return await flush(),null;if(choice==="pick"){let picked=isCode?await openEditorForCodePick(args.fimo,args.ctx,args.from,conflict):openEditorForPick(conflict);if(picked===null)return O2.warn("Empty buffer \u2014 treating as abort. Re-run with --resume to continue."),await flush(),null;resolutions.push({surface:conflict.surface,key:conflict.key,choice:"pick",pickedValue:picked})}else resolutions.push({surface:conflict.surface,key:conflict.key,choice});scheduleSave()}return await flush(),resolutions}__name(resolveConflictsInteractive,"resolveConflictsInteractive");async function printConflictWithContext(fimo,ctx,fromBranch,conflict,p2){console.log(renderConflict(conflict,p2));try{let drill=await fetchDrillContext({fimo,ctx,fromBranch,conflict,p:p2});drill&&console.log(drill)}catch{}}__name(printConflictWithContext,"printConflictWithContext");async function commitResolutions(args){let resolved;try{resolved=legacyMergeResult(await args.fimo.execute("branches.resolveMerge",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from,mergeId:args.mergeId,resolutions:args.resolutions.map(portableResolution)}))}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESOLVE_FAILED",message:`Resolve failed: ${err.message}`});return}if(!resolved.ok){ui.error({command:"merge",code:"MERGE_RESOLUTION_REJECTED",message:"Server rejected the resolution batch. Run `fimo diff` and try again."});return}ui.result({command:"merge",data:resolved,render:__name(rctx=>renderMergeSuccess(resolved,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")})}__name(commitResolutions,"commitResolutions");async function resumeMerge(args){let hydration;try{let portableHydration=await args.fimo.execute("branches.mergeConflicts",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from});hydration={...portableHydration,conflicts:portableHydration.conflicts.map(legacyConflict),draftResolutions:portableHydration.draftResolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESUME_FAILED",message:`Failed to load in-progress merge: ${err.message}`});return}if(hydration.status!=="in_progress"&&hydration.status!=="conflicts"){ui.error({command:"merge",code:"MERGE_NOT_RESUMABLE",message:`Merge ${hydration.mergeId} is ${hydration.status}; nothing to resume.`});return}if(hydration.conflicts.length===0){ui.info({command:"merge",message:"No conflicts to resolve \u2014 submitting empty batch."}),await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions:[]});return}mt(args.p.bold(`Resuming merge ${args.from} \u2192 ${args.ctx.branch}`)),O2.info(`${hydration.draftResolutions.length} of ${hydration.conflicts.length} conflict${hydration.conflicts.length===1?"":"s"} already drafted`);let resolutions=await resolveConflictsInteractive({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,conflicts:hydration.conflicts,drafted:hydration.draftResolutions,p:args.p,acceptDefaults:args.options.yes===!0});if(resolutions===null){ui.info({command:"merge",message:"Cancelled \u2014 draft kept. Run --resume again to continue."});return}await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions})}__name(resumeMerge,"resumeMerge");function openEditorForPick(conflict){let editor=process.env.EDITOR??process.env.VISUAL??"nano",tmp=mkdtempSync(path43.join(tmpdir3(),"fimo-merge-")),file=path43.join(tmp,`${conflict.surface}-${sanitiseKey(conflict.key)}.json`),seed=conflict.childValue!==void 0?JSON.stringify(conflict.childValue,null,2):`// Replace this comment with the resolved value as JSON
|
|
911
|
-
""`;writeFileSync5(file,seed,"utf8"),spawnSync3(editor,[file],{stdio:"inherit"});let raw=
|
|
911
|
+
""`;writeFileSync5(file,seed,"utf8"),spawnSync3(editor,[file],{stdio:"inherit"});let raw=readFileSync11(file,"utf8").trim();if(raw===""||raw===seed.trim())return null;try{return JSON.parse(raw)}catch{return raw}}__name(openEditorForPick,"openEditorForPick");async function openEditorForCodePick(fimo,ctx,fromBranch,conflict){let filePath=conflict.code?.path??conflict.key,seed="",seedLoaded=!1;try{seed=(await fimo.execute("branches.codeConflict",{projectId:ctx.projectId,branch:ctx.branch,from:fromBranch,path:filePath})).result.content??"",seedLoaded=!0}catch{O2.warn(`Could not load the 3-way merge for ${filePath}; leaving it unresolved. Re-run with --resume.`)}let editor=process.env.EDITOR??process.env.VISUAL??"nano",tmp=mkdtempSync(path43.join(tmpdir3(),"fimo-merge-")),ext=path43.extname(filePath)||".txt",file=path43.join(tmp,`${sanitiseKey(filePath)}${ext}`);writeFileSync5(file,seed,"utf8"),spawnSync3(editor,[file],{stdio:"inherit"});let raw=readFileSync11(file,"utf8");return raw.trim()===""&&(seed.trim()!==""||!seedLoaded)?null:((raw.includes("<<<<<<<")||raw.includes(">>>>>>>"))&&O2.warn("Conflict markers remain \u2014 they will be committed as-is. Re-run with --resume to fix."),raw)}__name(openEditorForCodePick,"openEditorForCodePick");function sanitiseKey(key){return key.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,60)}__name(sanitiseKey,"sanitiseKey");init_esm();init_dist();init_auth();init_config();init_project_services();init_project();import fs41 from"node:fs";import path44 from"node:path";var MIGRATION_DIR=path44.join(".fimo","migration"),MigrateCommandError=class extends Error{static{__name(this,"MigrateCommandError")}code;hint;constructor(code2,message,opts={}){super(message),this.code=code2,opts.hint!==void 0&&(this.hint=opts.hint)}},MigrateCancelled=class extends Error{static{__name(this,"MigrateCancelled")}constructor(message="Cancelled."){super(message)}};function emitMigrateError(command,error,fallbackCode){if(error instanceof MigrateCancelled){ui.info({command,message:error.message});return}if(error instanceof MigrateCommandError){ui.error({command,code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}});return}ui.error({command,code:fallbackCode,message:error instanceof Error?error.message:String(error)})}__name(emitMigrateError,"emitMigrateError");function isMigrationSourceUrl(value){let target=value.trim();return/^https?:\/\//i.test(target)?!0:/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?(\/|$)/i.test(target)}__name(isMigrationSourceUrl,"isMigrationSourceUrl");async function migrateInitCommand(targetArg,options){let command="migrate init";try{let{receipt,scaffoldWarnings}=await runMigrateInit(targetArg??options.cwd,options);await reportMigration(receipt.project_id,"didStartMigration",{sourcePlatform:receipt.source_platform}),await reportMigration(receipt.project_id,"didEndMigration",{sourcePlatform:receipt.source_platform,success:!0}),ui.result({command,data:receipt,render:__name(()=>renderInitReceipt(receipt),"render"),warnings:scaffoldWarnings.length>0?scaffoldWarnings:void 0,hint:`Load the fimo-migration skill (\`fimo skills get fimo-migration\`), read the source site yourself, and plan the migration in ${path44.join(receipt.migration_dir,"migration-plan.md")}`})}catch(error){emitMigrateError(command,error,"COMMAND_FAILED")}}__name(migrateInitCommand,"migrateInitCommand");async function runMigrateInit(dirArg,options){if(!dirArg)throw new MigrateCommandError("DIRECTORY_REQUIRED","A target project directory is required.",{hint:"Run `fimo migrate init <dir> --project-id <projectId>`, or `--org <organizationId>` to create a new project."});if(isMigrationSourceUrl(dirArg))throw new MigrateCommandError("DIRECTORY_REQUIRED","`fimo migrate init` takes a target directory, not a URL.",{hint:"Set the target up with `fimo migrate init <dir> --project-id <projectId>` (or `--org <organizationId>`), then read the source site yourself with a browser \u2014 the CLI no longer crawls it."});let sourcePlatform=parseSourcePlatform(options.sourcePlatform),explicitDir=path44.resolve(dirArg);if(fs41.existsSync(resolveProjectSettingsPath(explicitDir))){let settings=loadProjectSettings(explicitDir);if(options.projectId&&options.projectId!==settings.projectId)throw new MigrateCommandError("PROJECT_ID_MISMATCH",`${explicitDir} is already linked to project ${settings.projectId}, not ${options.projectId}.`,{hint:"Drop --project-id to reuse the existing link, or pass a different target directory."});let framework=assertRequestedFramework(explicitDir,options.framework);return{receipt:buildInitReceipt(explicitDir,settings.projectId,settings.name,requireMigrateAuth(),framework,sourcePlatform),scaffoldWarnings:[]}}if(fs41.existsSync(explicitDir)&&fs41.readdirSync(explicitDir).length>0)throw new MigrateCommandError("DIRECTORY_NOT_EMPTY",`Refusing to set up a migration target in non-empty directory ${explicitDir}.`,{hint:"Pass a linked Fimo project directory or an empty/new directory."});let outcome=await runInit(dirArg,{...options,framework:options.framework??"react-router",skills:!1,origin:"migration"});switch(outcome.status){case"ok":{let creds=readCredentials(loadConfig());return{receipt:buildInitReceipt(outcome.data.target_dir,outcome.data.project_id,outcome.data.project_name,creds?.user?.email??null,assertRequestedFramework(outcome.data.target_dir,options.framework),sourcePlatform),scaffoldWarnings:outcome.warnings}}case"cancelled":throw new MigrateCancelled;case"info":throw new MigrateCancelled(outcome.message);case"error":throw new MigrateCommandError(outcome.code,outcome.message,{hint:outcome.code==="NOT_AUTHENTICATED"?"Run `fimo login` first, then re-run `fimo migrate init`.":outcome.hint})}}__name(runMigrateInit,"runMigrateInit");function parseSourcePlatform(value){let normalized=value?.trim().toLowerCase();if(!normalized)return"unknown";let platform4=MIGRATION_SOURCE_PLATFORMS.find(candidate=>candidate===normalized);if(!platform4)throw new MigrateCommandError("SOURCE_PLATFORM_INVALID",`Unknown source platform "${value}".`,{hint:`Use one of: ${MIGRATION_SOURCE_PLATFORMS.join(", ")}.`});return platform4}__name(parseSourcePlatform,"parseSourcePlatform");async function reportMigration(projectId,event,properties){try{await createTelemetryService(loadConfig()).trackProjectEvent(projectId,event,properties)}catch{}}__name(reportMigration,"reportMigration");function requireMigrateAuth(){let creds=readCredentials(loadConfig());if(!creds?.access_token)throw new MigrateCommandError("NOT_AUTHENTICATED","You are not signed in to Fimo.",{hint:"Run `fimo login` first, then re-run `fimo migrate init`."});return creds.user?.email??null}__name(requireMigrateAuth,"requireMigrateAuth");function buildInitReceipt(projectRoot,projectId,projectName,user,framework,sourcePlatform){let migrationDir=path44.join(projectRoot,MIGRATION_DIR);return fs41.mkdirSync(migrationDir,{recursive:!0}),{mode:"source-backed",authenticated:!0,user,project_id:projectId,project_name:projectName,target_dir:projectRoot,migration_dir:migrationDir,framework,source_platform:sourcePlatform,ready:!0}}__name(buildInitReceipt,"buildInitReceipt");function readTargetFramework(projectRoot){let configPath=resolveProjectConfigPath(projectRoot);if(!fs41.existsSync(configPath))return null;try{let config=JSON.parse(fs41.readFileSync(configPath,"utf8"));return typeof config.runtime?.framework=="string"?config.runtime.framework:null}catch{return null}}__name(readTargetFramework,"readTargetFramework");function assertRequestedFramework(projectRoot,requestedFramework){let actualFramework=readTargetFramework(projectRoot);if(!requestedFramework)return actualFramework;let requested=requestedFramework.trim().toLowerCase();if(!actualFramework||actualFramework.trim().toLowerCase()!==requested)throw new MigrateCommandError("FRAMEWORK_MISMATCH",actualFramework?`Migration target uses ${actualFramework}, but ${requestedFramework} was requested.`:`Migration target does not declare runtime.framework, but ${requestedFramework} was requested.`,{hint:"Recreate or relink the target with the requested framework before importing migration data."});return actualFramework}__name(assertRequestedFramework,"assertRequestedFramework");function renderInitReceipt(receipt){return["Mode: source-backed",`Auth: signed in${receipt.user?` as ${receipt.user}`:""}`,`Project: ${receipt.project_name} (${receipt.project_id})`,`Target: ${receipt.target_dir} (linked)`,`Framework: ${receipt.framework??"unknown"}`,`Source: ${receipt.source_platform}`,`Migration dir: ${receipt.migration_dir}`,"Ready: yes \u2014 no schemas, entries, assets, or forms were written"].join(`
|
|
912
912
|
`)}__name(renderInitReceipt,"renderInitReceipt");init_dist();init_project_context();function padRight(s,width){return s.length>=width?s:s+" ".repeat(width-s.length)}__name(padRight,"padRight");function fmtUsd(n){let trimmed=n.toFixed(4).replace(/0+$/,"").replace(/\.$/,"");return trimmed.includes(".")?trimmed:`${trimmed}.00`}__name(fmtUsd,"fmtUsd");function priceRate(price){let unit=price.unit.replace(/s$/,"");return`${price.confidence==="metered"?"~":""}$${fmtUsd(price.unitPrice)} / ${unit}`}__name(priceRate,"priceRate");function bestFor(description){let start=description.indexOf("Best for:");if(start===-1)return`${description.split(". ")[0]}.`;let rest=description.slice(start),notFor=rest.indexOf("Not for:");return(notFor===-1?rest:rest.slice(0,notFor)).replace(/^Best for:\s*/,"").trim()}__name(bestFor,"bestFor");function flagSignature(flag2){if(flag2.type==="boolean")return`--${flag2.name}`;let type=flag2.enumValues?.length?flag2.enumValues.join("|"):flag2.type;return`--${flag2.name} <${type}>`}__name(flagSignature,"flagSignature");function flagMeta(flag2){let parts=[flag2.required?"required":"optional"];return flag2.isArray&&parts.push("repeatable"),flag2.defaultValue!==void 0&&parts.push(`default ${JSON.stringify(flag2.defaultValue)}`),parts.join(", ")}__name(flagMeta,"flagMeta");function flagExample(flag2){let name=`--${flag2.name}`;if(flag2.type==="boolean")return flag2.defaultValue===!0?`--no-${flag2.name}`:name;let value;return flag2.enumValues?.length?value=String(flag2.enumValues[0]):/url|image/i.test(flag2.name)?value="<url>":flag2.type==="integer"||flag2.type==="number"?value=flag2.defaultValue!==void 0?String(flag2.defaultValue):"<n>":value='"\u2026"',flag2.isArray?`${name} ${value} ${name} ${value}`:`${name} ${value}`}__name(flagExample,"flagExample");async function modelsListCommand(opts){let context=await getProjectContext({cwd:opts.cwd}),models=await createModelCatalogService().list(context.projectId,{modality:opts.modality,tag:opts.tag,q:opts.search,category:opts.category});if(models.length===0){ui.info({command:"models list",message:"No models match the filter."});return}ui.result({command:"models list",data:{models},render:__name(()=>renderModelsListHuman(models,opts.extended===!0),"render")})}__name(modelsListCommand,"modelsListCommand");function renderModelsListHuman(models,extended){let groups=new Map;for(let m of models){let arr=groups.get(m.modality)??[];arr.push(m),groups.set(m.modality,arr)}let modalityOrder=["image","video","audio"],sortedModalities=Array.from(groups.keys()).sort((a,b)=>modalityOrder.indexOf(a)-modalityOrder.indexOf(b)),out=[],first=!0;for(let modality of sortedModalities){first||out.push(""),first=!1;let group=groups.get(modality)??[];if(out.push(modality.toUpperCase()),extended){for(let m of group)out.push(renderExtendedEntry(m));continue}let nameWidth=Math.max(...group.map(m=>m.id.length));for(let m of group){let headline=m.description.split(". ")[0],tags=m.tags.length>0?`[${m.tags.join(", ")}]`:"",price=m.price?` ${priceRate(m.price)}`:"";out.push(` ${padRight(m.id,nameWidth)} ${tags}${price}`),out.push(` ${padRight("",nameWidth)} ${headline}.`)}}return out.join(`
|
|
913
913
|
`)}__name(renderModelsListHuman,"renderModelsListHuman");function renderExtendedEntry(m){let required=m.flags.filter(f=>f.required).map(f=>`--${f.name}`),optionalCount=m.flags.length-required.length,lines=[],row2=__name((label,value)=>{lines.push(` ${`${label}:`.padEnd(10)}${value}`)},"row"),flagsValue=m.flags.length===0?"none":`${required.length?`${required.join(", ")} (required)`:"none required"}${optionalCount?`, ${optionalCount} more`:""} \u2014 fimo models show ${m.id}`;return lines.push(` ${m.id} (${m.provider})`),row2("tags",m.tags.join(", ")||"\u2014"),m.price&&row2("price",priceRate(m.price)),row2("best for",bestFor(m.description)),row2("flags",flagsValue),lines.join(`
|
|
914
914
|
`)}__name(renderExtendedEntry,"renderExtendedEntry");async function modelsShowCommand(modelKey,opts){let context=await getProjectContext({cwd:opts.cwd}),model=await createModelCatalogService().get(context.projectId,modelKey);model||(ui.error({command:"models show",code:"UNKNOWN_MODEL",message:`Unknown model: "${modelKey}".`,hint:"Run `fimo models list` to see available names."}),process.exit(78)),ui.result({command:"models show",data:model,render:__name(()=>renderModelHuman(model),"render")})}__name(modelsShowCommand,"modelsShowCommand");function renderModelHuman(model){let lines=[];if(lines.push(model.displayName),lines.push(` id: ${model.id}`),lines.push(` provider: ${model.provider}`),lines.push(` source: ${model.source}`),lines.push(` modality: ${model.modality}`),lines.push(` tags: ${model.tags.join(", ")||"\u2014"}`),lines.push(""),lines.push(` ${model.description}`),model.price&&(lines.push(""),lines.push(" PRICING"),lines.push(` ${priceRate(model.price)}`),model.price.confidence==="metered"?lines.push(" (metered \u2014 final bill set by provider usage)"):model.price.confidence==="estimated"&&lines.push(" (estimated \u2014 exact quantity not known until the call runs)")),lines.push(""),lines.push(" OPTIONS"),model.flags.length===0)return lines.push(" (none)"),lines.join(`
|
|
915
915
|
`);for(let flag2 of model.flags){lines.push(""),lines.push(` ${flagSignature(flag2)} ${flagMeta(flag2)}`),flag2.description&&lines.push(` ${flag2.description}`);let repeatNote=flag2.isArray?" (repeat the flag for each value)":"";lines.push(` e.g. ${flagExample(flag2)}${repeatNote}`)}return lines.join(`
|
|
916
|
-
`)}__name(renderModelHuman,"renderModelHuman");init_dist();init_auth();init_config();init_sdk_transport();async function orgsListCommand(){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),activeId=requireCredentials(cfg)?.activeOrganization?.id,{data:orgs2}=await fimo.execute("organizations.list",{});if(orgs2.length===0){ui.info({command:"orgs list",message:"No organizations found for this account."});return}ui.table({command:"orgs list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"slug",label:"SLUG"}],rows:orgs2.map(org=>({id:org.id,name:org.name,slug:org.slug})),isActive:__name(row2=>row2.id===activeId,"isActive")})}__name(orgsListCommand,"orgsListCommand");async function orgsMembersCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),creds=requireCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"orgs members",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let members=await fimo.execute("organizations.members",{organizationId});if(members.length===0){ui.info({command:"orgs members",message:"No members found."});return}ui.table({command:"orgs members",columns:[{key:"role",label:"ROLE"},{key:"email",label:"EMAIL"},{key:"name",label:"NAME"}],rows:members.map(m=>({role:m.role,email:m.user?.email??"\u2014",name:m.user?.name??"\u2014"}))})}__name(orgsMembersCommand,"orgsMembersCommand");init_esm();init_dist();import fs42 from"node:fs";init_config();init_sdk_transport();init_project_context();init_project();var PAGE_PARAM_KEYS=["schema","queryField","displayField"],LOCALE_PARAM_SEGMENT=/:(locale|lang|language)\*?(?=\/|$)/gi,MAX_EXPANDED_PAGE_INSTANCES=1e4;function configPathFor(cwd){return resolveFimoConfigPath(cwd)}__name(configPathFor,"configPathFor");function readPageRegistry(cwd,command){let file=configPathFor(cwd);fs42.existsSync(file)||(ui.error({command,code:"PAGE_REGISTRY_MISSING",message:"No fimo-config.json was found in this project."}),process.exit(1));let config;try{config=JSON.parse(fs42.readFileSync(file,"utf8"))}catch{ui.error({command,code:"CONFIG_PARSE_FAILED",message:"fimo-config.json is not valid JSON."}),process.exit(1)}return{config,routes:config.routes??{},file}}__name(readPageRegistry,"readPageRegistry");function pageStatus(route){let
|
|
917
|
-
`)}__name(writePageRegistry,"writePageRegistry");var COLLECTION_QUERY_KEYS=new Set(["where","search","sort","limit","offset","fields","populate"]);function stringOrStrings(value){return typeof value=="string"&&value.length>0||Array.isArray(value)&&value.length>0&&value.every(item=>typeof item=="string"&&item.length>0)}__name(stringOrStrings,"stringOrStrings");function parseCollectionQuery(raw,subject){let invalid=__name(message=>fail("pages set","PAGE_SOURCE_QUERY_INVALID",`${subject} ${message}`),"invalid");if(!isObject(raw)||Object.keys(raw).some(key=>!COLLECTION_QUERY_KEYS.has(key)))return invalid("has an invalid query.");if(raw.where!==void 0&&!isObject(raw.where))return invalid("query where must be an object.");if(raw.search!==void 0&&typeof raw.search!="string")return invalid("query search must be a string.");for(let key of["sort","fields","populate"])if(raw[key]!==void 0&&!stringOrStrings(raw[key]))return invalid(`query ${key} must be a field or field list.`);return raw.limit!==void 0&&(!Number.isInteger(raw.limit)||raw.limit<1||raw.limit>100)?invalid("query limit must be between 1 and 100."):raw.offset!==void 0&&(!Number.isInteger(raw.offset)||raw.offset<0)?invalid("query offset must be zero or greater."):raw}__name(parseCollectionQuery,"parseCollectionQuery");function parseSources(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return fail("pages set","PAGE_SOURCES_INVALID","Sources must be a JSON object keyed by a stable source name.")}if(!isObject(parsed)||Object.keys(parsed).length===0)return fail("pages set","PAGE_SOURCES_INVALID","Sources must be a non-empty JSON object. Use --clear-sources to remove them.");let sources={};for(let[name,rawSource]of Object.entries(parsed)){if(!/^[A-Za-z][\w-]*$/.test(name)||!isObject(rawSource)||typeof rawSource.type!="string")return fail("pages set","PAGE_SOURCE_INVALID",`Source "${name}" needs a stable name and a valid type.`);if(rawSource.type==="labels"){if(!Array.isArray(rawSource.match)||rawSource.match.length===0||!rawSource.match.every(item=>typeof item=="string"))return fail("pages set","PAGE_SOURCE_INVALID",`Labels source "${name}" requires a non-empty match array.`);let invalidPattern=rawSource.match.find(pattern=>!isLabelPattern(pattern));if(invalidPattern)return fail("pages set","PAGE_LABEL_PATTERN_INVALID",`Label pattern "${invalidPattern}" must be an exact key or a literal prefix ending with ".*".`);sources[name]={type:"labels",match:[...new Set(rawSource.match)]};continue}if(rawSource.type==="single"){if(typeof rawSource.schema!="string"||!rawSource.schema)return fail("pages set","PAGE_SOURCE_INVALID",`Single source "${name}" requires a schema.`);sources[name]={type:"single",schema:rawSource.schema};continue}if(rawSource.type!=="collection"||typeof rawSource.schema!="string"||!rawSource.schema)return fail("pages set","PAGE_SOURCE_INVALID",`Source "${name}" must be labels, single, or collection.`);let query=rawSource.query===void 0?void 0:parseCollectionQuery(rawSource.query,`Collection source "${name}"`);sources[name]={type:"collection",schema:rawSource.schema,...query?{query}:{}}}return sources}__name(parseSources,"parseSources");function queryFields2(query){if(!query)return[];let fields=new Set;for(let field of Object.keys(query.where??{}))field.startsWith("$")||fields.add(field.split(".")[0]);for(let sort of fieldList2(query.sort))fields.add(sort.replace(/^-/,"").split(".")[0]);for(let field of[...fieldList2(query.fields),...fieldList2(query.populate)])fields.add(field.split(".")[0]);return[...fields]}__name(queryFields2,"queryFields");function entryFields(schema){return new Set([...Object.keys(schema.fields??{}),"id","slug"])}__name(entryFields,"entryFields");async function assertParamExpressions(query,subject,available,getSchema){for(let expression of pageSourceParamExpressions(query)){let parsed=parsePageParamExpression(expression);parsed||fail("pages set","PAGE_PARAM_EXPRESSION_INVALID",`Expression "${expression}" must use $params.<param>.<field>.`);let binding=available[parsed.param];binding||fail("pages set","PAGE_PARAM_UNKNOWN",`${subject} references param "${parsed.param}", which this page does not bind before it.`);let boundSchema=await getSchema(binding.schema),field=parsed.field.split(".")[0];(!boundSchema||!entryFields(boundSchema).has(field))&&fail("pages set","PAGE_PARAM_FIELD_UNKNOWN",`Field "${field}" does not exist on bound schema "${binding.schema}" (${expression}).`)}}__name(assertParamExpressions,"assertParamExpressions");function uniqueSourceName(sources,preferred){if(!sources[preferred])return preferred;let suffix=2;for(;sources[`${preferred}-${suffix}`];)suffix+=1;return`${preferred}-${suffix}`}__name(uniqueSourceName,"uniqueSourceName");function normalizedPageSources(route){let sources={...route.sources??{}},labels2=(route.content?.labels??[]).filter(isLabelPattern);labels2.length>0&&!Object.values(sources).some(source=>source.type==="labels")&&(sources[uniqueSourceName(sources,"labels")]={type:"labels",match:[...new Set(labels2)]});for(let schema of route.content?.singles??[]){if(!schema||Object.values(sources).some(source=>source.type==="single"&&source.schema===schema))continue;let preferred=`single-${schema}`;sources[uniqueSourceName(sources,preferred)]={type:"single",schema}}return sources}__name(normalizedPageSources,"normalizedPageSources");async function pagesListCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),{config,routes}=readPageRegistry(cwd,"pages list"),templates=Object.entries(routes).filter(entry=>typeof entry[1]?.path=="string").map(([id,route])=>{let sources=normalizedPageSources(route);return{id,path:route.path,label:route.label??route.path,status:pageStatus(route),...route.params?{params:route.params}:{},...Object.keys(sources).length>0?{sources}:{}}});if(!options.expand){ui.result({command:"pages list",data:{pages:templates},render:__name(()=>templates.length===0?"No pages are registered yet. Add one with `fimo pages set <id> --path <path>`.":templates.map(page=>`${page.status.padEnd(15)} ${page.path} (id ${page.id})`).join(`
|
|
918
|
-
`),"render")});return}let{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let i18n=config.i18n,defaultLocale=i18n?.defaultLocale??i18n?.locales?.[0]??"en",instances=[],skipped=[];for(let page of templates){let routePath=substituteLocaleParams(page.path,defaultLocale),contentParams=pageContentParamNames(routePath);if(contentParams.length===0){instances.push({id:page.id,path:routePath});continue}if(page.status!=="dynamic:bound"){skipped.push({id:page.id,path:page.path,reason:"no schema binding; bind it with `fimo pages set`"});continue}let materialized=[{path:routePath,params:{}}],failedReason;for(let param of contentParams){let binding=page.params?.[param];if(!binding){failedReason=`no binding for "${param}"`;break}let expanded=[],failExpansionLimit=__name(()=>fail("pages list","PAGE_EXPANSION_LIMIT_EXCEEDED",`Page "${page.id}" expands beyond ${MAX_EXPANDED_PAGE_INSTANCES.toLocaleString()} instances. Narrow its param queries with where or limit before using --expand.`),"failExpansionLimit");for(let candidate of materialized){let resolution=resolvePageSourceQuery(binding.query,candidate.params);if(!resolution.ok)continue;let rows=await fetchEntries(content2,ctx.projectId,binding.schema,resolution.query,binding.queryField,MAX_EXPANDED_PAGE_INSTANCES-expanded.length,failExpansionLimit);for(let row2 of rows){let value=entryFieldValue(row2,binding.queryField);value==null||value===""||(expanded.length>=MAX_EXPANDED_PAGE_INSTANCES&&failExpansionLimit(),expanded.push({path:substituteRouteParam(candidate.path,param,String(value)),params:{...candidate.params,[param]:row2}}))}}if(expanded.length===0){failedReason=`no ${binding.schema} entries to materialize`;break}materialized=expanded}if(failedReason){skipped.push({id:page.id,path:page.path,reason:failedReason});continue}instances.push(...materialized.map(instance=>({id:page.id,path:instance.path,from:Object.values(page.params??{}).map(binding=>`${binding.schema}.${binding.queryField}`).join(", ")})))}ui.result({command:"pages list",data:{pages:templates,instances,skipped},render:__name(()=>[...instances.map(instance=>`${instance.path}${instance.from?` (${instance.id} \u2190 ${instance.from})`:""}`),...skipped.map(entry=>`SKIPPED ${entry.path}: ${entry.reason}`),`${instances.length} page instance(s) from ${templates.length} template(s)`].join(`
|
|
919
|
-
`),"render")})}__name(pagesListCommand,"pagesListCommand");function parseParams(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(!parsed||typeof parsed!="object"||Array.isArray(parsed)||Object.keys(parsed).length===0)return null;for(let[param,value]of Object.entries(parsed)){if(!isObject(value))return null;for(let key of PAGE_PARAM_KEYS)if(typeof value[key]!="string"||!value[key])return null;value.query!==void 0&&parseCollectionQuery(value.query,`Param "${param}"`)}return parsed}__name(parseParams,"parseParams");async function pagesSetCommand(id,options,cmd){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages set");options.path!==void 0||options.label!==void 0||options.group!==void 0||options.sources!==void 0||options.clearSources===!0||options.icon!==void 0||options.params!==void 0||options.clearParams===!0||(ui.error({command:"pages set",code:"PAGE_SET_EMPTY",message:"Nothing to set. Pass --path, --label, --group, --sources, --clear-sources, --icon, --params, and/or --clear-params."}),process.exit(1)),options.sources!==void 0&&options.clearSources&&fail("pages set","PAGE_SOURCES_CONFLICT","Pass either --sources or --clear-sources, not both."),options.params!==void 0&&options.clearParams&&fail("pages set","PAGE_PARAMS_CONFLICT","Pass either --params or --clear-params, not both."),options.icon!==void 0&&options.icon!==""&&!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options.icon)&&(ui.error({command:"pages set",code:"PAGE_ICON_INVALID",message:'Icons use kebab-case Lucide names, for example "newspaper". Pass an empty value to clear it.'}),process.exit(1));let existing=routes[id];!existing&&!options.path&&(ui.error({command:"pages set",code:"PAGE_NOT_FOUND",message:`No page "${id}" exists in the registry. Creating one requires --path.`}),process.exit(1)),options.path!==void 0&&(!options.path.startsWith("/")||/[[\]]/.test(options.path))&&(ui.error({command:"pages set",code:"PAGE_PATH_INVALID",message:'Page paths start with "/" and use :param syntax, never [param].'}),process.exit(1));let next={...existing??{}};if(existing?.content){let normalizedSources=normalizedPageSources(existing);Object.keys(normalizedSources).length>0&&(next.sources=normalizedSources),delete next.content}if(options.path!==void 0&&(next.path=options.path),options.label!==void 0&&(options.label===""?delete next.label:next.label=options.label),options.group!==void 0&&(options.group===""?delete next.group:next.group=options.group),options.icon!==void 0&&(options.icon===""?delete next.icon:next.icon=options.icon),options.sources!==void 0&&(next.sources=parseSources(options.sources)),options.clearSources&&delete next.sources,options.params!==void 0){let params=parseParams(options.params)??void 0;params||(ui.error({command:"pages set",code:"PAGE_PARAMS_INVALID",message:'Expected {"<param>":{"schema":"<Type>","queryField":"<field>","displayField":"<field>"}}.'}),process.exit(1)),next.params=params}if(options.clearParams&&delete next.params,options.path!==void 0&&options.params===void 0&&!options.clearParams&&next.params){let bindableParams=new Set(pageContentParamNames(next.path??"")),retainedParams=Object.fromEntries(Object.entries(next.params).filter(([param])=>bindableParams.has(param)));Object.keys(retainedParams).length>0?next.params=retainedParams:delete next.params}let projectContextPromise,schemas3=new Map,getSchema=__name(async schemaName=>{if(schemas3.has(schemaName))return schemas3.get(schemaName)??null;projectContextPromise??=bootstrapProjectCommand(options,cmd);let{ctx,fimo}=await projectContextPromise;await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let schema;try{schema=await fimo.execute("schemas.get",{projectId:ctx.projectId,branch:ctx.branch,typeName:schemaName})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==404)throw error;schema=null}return schemas3.set(schemaName,schema),schema},"getSchema"),effectivePath=next.path??"",contentParams=pageContentParamNames(effectivePath),effectiveParams=next.params??{};for(let[param,binding]of Object.entries(effectiveParams)){contentParams.includes(param)||fail("pages set","PAGE_PARAM_UNKNOWN",`Param "${param}" does not exist in the page path "${effectivePath}".`);let schema=await getSchema(binding.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${binding.schema}" does not exist (param "${param}").`),schema.isSingleton!==!1&&fail("pages set","PAGE_PARAM_KIND_INVALID",`Param "${param}" needs a known Collection schema, but "${binding.schema}" is not marked as a Collection.`);let fields=entryFields(schema);for(let key of["queryField","displayField"])fields.has(binding[key])||fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${binding[key]}" does not exist on "${binding.schema}".`);if(!["id","slug"].includes(binding.queryField)){let definition=schema.fields?.[binding.queryField];(!isObject(definition)||definition.required!==!0)&&fail("pages set","PAGE_QUERY_FIELD_OPTIONAL",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "required": true.`),definition.unique!==!0&&fail("pages set","PAGE_QUERY_FIELD_NOT_UNIQUE",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "unique": true.`)}if(!binding.query)continue;let queryableFields2=new Set([...fields,"createdAt","updatedAt"]),unknownField=queryFields2(binding.query).find(field=>!queryableFields2.has(field));unknownField&&fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${unknownField}" does not exist on "${binding.schema}".`);let selectedBefore=Object.fromEntries(contentParams.slice(0,contentParams.indexOf(param)).flatMap(earlier=>effectiveParams[earlier]?[[earlier,effectiveParams[earlier]]]:[]));await assertParamExpressions(binding.query,`Param "${param}"`,selectedBefore,getSchema)}for(let[sourceName,source]of Object.entries(next.sources??{})){if(source.type==="labels")continue;let schema=await getSchema(source.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${source.schema}" does not exist (source "${sourceName}").`),source.type==="single"&&schema.isSingleton!==!0&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Single, but "${source.schema}" is not marked as a Single.`),source.type==="collection"&&schema.isSingleton!==!1&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Collection, but "${source.schema}" is not marked as a Collection.`);let query=source.type==="collection"?source.query:void 0,fields=new Set([...entryFields(schema),"createdAt","updatedAt"]),unknownSourceField=queryFields2(query).find(field=>!fields.has(field));unknownSourceField&&fail("pages set","PAGE_SOURCE_FIELD_UNKNOWN",`Field "${unknownSourceField}" does not exist on "${source.schema}" (source "${sourceName}").`),await assertParamExpressions(query,`Source "${sourceName}"`,effectiveParams,getSchema)}routes[id]=next,writePageRegistry(file,config,routes),ui.result({command:"pages set",data:{id,page:next},render:__name(()=>`Page "${id}" now points to ${next.path}.`,"render")})}__name(pagesSetCommand,"pagesSetCommand");function pagesDeleteCommand(id,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages delete");routes[id]||fail("pages delete","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),delete routes[id],writePageRegistry(file,config,routes),ui.result({command:"pages delete",data:{id},render:__name(()=>`Deleted page "${id}" from the registry.`,"render")})}__name(pagesDeleteCommand,"pagesDeleteCommand");function pagesRenameCommand(id,nextId,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages rename");routes[id]||fail("pages rename","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),id!==nextId&&routes[nextId]&&fail("pages rename","PAGE_ALREADY_EXISTS",`Page "${nextId}" already exists in the registry.`);let renamed=Object.fromEntries(Object.entries(routes).map(([routeId,route])=>[routeId===id?nextId:routeId,route]));writePageRegistry(file,config,renamed),ui.result({command:"pages rename",data:{id:nextId,previousId:id},render:__name(()=>`Renamed page "${id}" to "${nextId}".`,"render")})}__name(pagesRenameCommand,"pagesRenameCommand");init_esm();init_dist();init_config();init_project_services();init_project_context();var WAIT_TIMEOUT_MS=300*1e3,FIRST_POLL_MS=2e3,MAX_POLL_MS=15e3,POLL_GROWTH=1.5,PreviewUrlError=class extends Error{constructor(failure){super(failure.message);this.failure=failure;this.name="PreviewUrlError"}static{__name(this,"PreviewUrlError")}};function noHostedPreview(branch){return isProductionBranch(branch)?{message:`Branch '${branch}' is production and has no hosted preview.`,hint:"Publish with `fimo deploy --publish` and open the live site instead."}:{message:`Branch '${branch}' has no hosted preview yet.`,hint:"Run `fimo deploy` to push a change; that is what asks for a hosted preview."}}__name(noHostedPreview,"noHostedPreview");function errorMessage3(error){return error instanceof Error?error.message:String(error)}__name(errorMessage3,"errorMessage");async function previewUrlCommand(options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.preview.url",{projectId:ctx.projectId,branch:ctx.branch});let studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,ctx.branch);try{let sandbox=createSandboxService(loadConfig(),ctx.branch),deadline=Date.now()+WAIT_TIMEOUT_MS,delayMs=FIRST_POLL_MS,hosted=await sandbox.getHostedPreview(ctx.projectId,ctx.branch);for(;;){if(hosted===null)throw new PreviewUrlError(noHostedPreview(ctx.branch));if(hosted.status==="ready")break;if(hosted.status==="failed")throw new PreviewUrlError({message:"The hosted preview build failed.",hint:"Fix the project, then run `fimo deploy` to build the Branch again."});if(Date.now()+delayMs>=deadline)throw new PreviewUrlError({message:hosted.status==="queued"?"The hosted preview is still waiting to build.":"The hosted preview is still building.",hint:`Try \`fimo preview url\` again in a moment, or watch the Branch in Fimo: ${studioUrl}`});await new Promise(resolve10=>setTimeout(resolve10,delayMs)),delayMs=Math.min(Math.round(delayMs*POLL_GROWTH),MAX_POLL_MS),hosted=await sandbox.getHostedPreview(ctx.projectId,ctx.branch)}let url=hosted.url;if(!url)throw new PreviewUrlError({message:"The hosted preview is ready but did not return a URL.",hint:`Open the Branch in Fimo: ${studioUrl}`});ui.result({command:"preview url",data:{project_id:ctx.projectId,branch:ctx.branch,env:ctx.branch,preview_url:url},render:__name(context=>terminalLink("Open preview",url,context.hyperlinks),"render")})}catch(error){ui.error({command:"preview url",code:"PREVIEW_URL_FAILED",message:`Failed to get preview URL: ${errorMessage3(error)}`,hint:error instanceof PreviewUrlError?error.failure.hint:`Open the Branch in Fimo while it builds: ${studioUrl}`})}}__name(previewUrlCommand,"previewUrlCommand");function registerPreviewCommands(program2){program2.command("preview").description("Inspect a Branch preview without deploying").command("url").description("Get the hosted preview URL for the current Branch (or --branch <name>) without deploying").option("-C, --cwd <dir>","Run against this directory instead of cwd").action((opts,cmd)=>previewUrlCommand(opts,cmd))}__name(registerPreviewCommands,"registerPreviewCommands");init_esm();init_dist();init_config();init_sdk_transport();import fs43 from"node:fs";import path45 from"node:path";function mergeManagedEnvBlock(existing,entries2,spec){let block=renderBlock(entries2,spec),normalized=existing.replace(/\r\n/g,`
|
|
916
|
+
`)}__name(renderModelHuman,"renderModelHuman");init_dist();init_auth();init_config();init_sdk_transport();async function orgsListCommand(){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),activeId=requireCredentials(cfg)?.activeOrganization?.id,{data:orgs2}=await fimo.execute("organizations.list",{});if(orgs2.length===0){ui.info({command:"orgs list",message:"No organizations found for this account."});return}ui.table({command:"orgs list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"slug",label:"SLUG"}],rows:orgs2.map(org=>({id:org.id,name:org.name,slug:org.slug})),isActive:__name(row2=>row2.id===activeId,"isActive")})}__name(orgsListCommand,"orgsListCommand");async function orgsMembersCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),creds=requireCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"orgs members",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let members=await fimo.execute("organizations.members",{organizationId});if(members.length===0){ui.info({command:"orgs members",message:"No members found."});return}ui.table({command:"orgs members",columns:[{key:"role",label:"ROLE"},{key:"email",label:"EMAIL"},{key:"name",label:"NAME"}],rows:members.map(m=>({role:m.role,email:m.user?.email??"\u2014",name:m.user?.name??"\u2014"}))})}__name(orgsMembersCommand,"orgsMembersCommand");init_esm();init_dist();import fs42 from"node:fs";init_config();init_sdk_transport();init_project_context();init_project();var PAGE_PARAM_KEYS=["schema","queryField","displayField"],ENTRY_PARAM_KEYS=new Set(["type",...PAGE_PARAM_KEYS,"query"]),LOCALE_PARAM_SEGMENT=/:(locale|lang|language)\*?(?=\/|$)/gi,MAX_EXPANDED_PAGE_INSTANCES=1e4;function configPathFor(cwd){return resolveFimoConfigPath(cwd)}__name(configPathFor,"configPathFor");function readPageRegistry(cwd,command){let file=configPathFor(cwd);fs42.existsSync(file)||(ui.error({command,code:"PAGE_REGISTRY_MISSING",message:"No fimo-config.json was found in this project."}),process.exit(1));let config;try{config=JSON.parse(fs42.readFileSync(file,"utf8"))}catch{ui.error({command,code:"CONFIG_PARSE_FAILED",message:"fimo-config.json is not valid JSON."}),process.exit(1)}return{config,routes:config.routes??{},file}}__name(readPageRegistry,"readPageRegistry");function pageStatus(route){let placeholders=pageContentParamNames(route.path??"");if(placeholders.length===0)return"static";let contentParams=pageContentParamNames(route.path??"",route.params);return contentParams.some(param=>!isEntryParamBinding(route.params?.[param]))?"dynamic:unbound":contentParams.length<placeholders.length?"dynamic:external":"dynamic:bound"}__name(pageStatus,"pageStatus");function entryFieldValue(entry,field){if(entry[field]!==void 0)return entry[field];let data=entry.data;if(data&&typeof data=="object")return data[field]}__name(entryFieldValue,"entryFieldValue");function responseRows(response){if(Array.isArray(response))return response;if(!response||typeof response!="object")return[];let data=response.data;return Array.isArray(data)?data:data&&typeof data=="object"&&Array.isArray(data.data)?data.data:[]}__name(responseRows,"responseRows");function responsePagination(response){if(!response||typeof response!="object")return null;let meta=response.meta;if(!meta||typeof meta!="object")return null;let{offset,limit,hasMore}=meta;return typeof offset=="number"&&typeof limit=="number"&&typeof hasMore=="boolean"?{offset,limit,hasMore}:null}__name(responsePagination,"responsePagination");function fieldList2(value){return typeof value=="string"?[value]:value??[]}__name(fieldList2,"fieldList");async function fetchEntries(api,projectId,schema,query,materializationField,maxRows,onLimitExceeded){let filters={};query.where&&Object.keys(query.where).length>0&&(filters.where=JSON.stringify(query.where)),query.search&&(filters.search=query.search);for(let[key,value]of[["sort",fieldList2(query.sort)],["fields",fieldList2(query.fields)],["populate",fieldList2(query.populate)]])value.length>0&&(filters[key]=value.join(","));let rows=[],offset=query.offset??0,selectedRows=0;for(;;){let remainingQueryRows=query.limit===void 0?100:Math.min(100,query.limit-selectedRows),response=await api.listEntries(projectId,schema,{...filters,limit:String(remainingQueryRows),offset:String(offset)}),pageRows=responseRows(response);selectedRows+=pageRows.length;let materializableRows=pageRows.filter(row2=>{let value=entryFieldValue(row2,materializationField);return value!=null&&value!==""});if(maxRows!==void 0&&rows.length+materializableRows.length>maxRows)throw onLimitExceeded?.(),new Error(`Entries for "${schema}" exceed the expansion limit.`);if(rows.push(...materializableRows),query.limit!==void 0&&selectedRows>=query.limit)return rows;let pagination=responsePagination(response);if(maxRows!==void 0&&rows.length===maxRows&&pagination?.hasMore)throw onLimitExceeded?.(),new Error(`Entries for "${schema}" exceed the expansion limit.`);if(!pagination){if(pageRows.length>=100)throw new Error(`Entries response for "${schema}" returned 100 rows without pagination metadata, so Pages cannot safely expand every entry.`);return rows}if(!pagination.hasMore)return rows;let nextOffset=pagination.offset+pagination.limit;if(nextOffset<=offset)throw new Error(`Entries pagination for "${schema}" did not advance past offset ${offset}.`);offset=nextOffset}}__name(fetchEntries,"fetchEntries");function substituteLocaleParams(routePath,locale){return locale?routePath.replace(LOCALE_PARAM_SEGMENT,()=>encodeURIComponent(locale)):routePath}__name(substituteLocaleParams,"substituteLocaleParams");function encodeRouteParam(value,catchAll){return catchAll?value.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(value)}__name(encodeRouteParam,"encodeRouteParam");function substituteRouteParam(routePath,param,value){return routePath.split("/").map(segment=>{let catchAll=segment.endsWith("*");return segment===`:${param}`||catchAll&&segment.slice(1,-1)===param?encodeRouteParam(value,catchAll):segment}).join("/")}__name(substituteRouteParam,"substituteRouteParam");function isLabelPattern(pattern){let wildcardIndex=pattern.indexOf("*");return wildcardIndex===-1||pattern.length>2&&pattern.endsWith(".*")&&wildcardIndex===pattern.length-1}__name(isLabelPattern,"isLabelPattern");function isObject(value){return!!value&&typeof value=="object"&&!Array.isArray(value)}__name(isObject,"isObject");function fail(command,code2,message){ui.error({command,code:code2,message}),process.exit(1)}__name(fail,"fail");function writePageRegistry(file,config,routes){config.routes=routes,fs42.writeFileSync(file,`${JSON.stringify(config,null,2)}
|
|
917
|
+
`)}__name(writePageRegistry,"writePageRegistry");var COLLECTION_QUERY_KEYS=new Set(["where","search","sort","limit","offset","fields","populate"]);function stringOrStrings(value){return typeof value=="string"&&value.length>0||Array.isArray(value)&&value.length>0&&value.every(item=>typeof item=="string"&&item.length>0)}__name(stringOrStrings,"stringOrStrings");function parseCollectionQuery(raw,subject){let invalid=__name(message=>fail("pages set","PAGE_SOURCE_QUERY_INVALID",`${subject} ${message}`),"invalid");if(!isObject(raw)||Object.keys(raw).some(key=>!COLLECTION_QUERY_KEYS.has(key)))return invalid("has an invalid query.");if(raw.where!==void 0&&!isObject(raw.where))return invalid("query where must be an object.");if(raw.search!==void 0&&typeof raw.search!="string")return invalid("query search must be a string.");for(let key of["sort","fields","populate"])if(raw[key]!==void 0&&!stringOrStrings(raw[key]))return invalid(`query ${key} must be a field or field list.`);return raw.limit!==void 0&&(!Number.isInteger(raw.limit)||raw.limit<1||raw.limit>100)?invalid("query limit must be between 1 and 100."):raw.offset!==void 0&&(!Number.isInteger(raw.offset)||raw.offset<0)?invalid("query offset must be zero or greater."):raw}__name(parseCollectionQuery,"parseCollectionQuery");function parseSources(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return fail("pages set","PAGE_SOURCES_INVALID","Sources must be a JSON object keyed by a stable source name.")}if(!isObject(parsed)||Object.keys(parsed).length===0)return fail("pages set","PAGE_SOURCES_INVALID","Sources must be a non-empty JSON object. Use --clear-sources to remove them.");let sources={};for(let[name,rawSource]of Object.entries(parsed)){if(!/^[A-Za-z][\w-]*$/.test(name)||!isObject(rawSource)||typeof rawSource.type!="string")return fail("pages set","PAGE_SOURCE_INVALID",`Source "${name}" needs a stable name and a valid type.`);if(rawSource.type==="labels"){if(!Array.isArray(rawSource.match)||rawSource.match.length===0||!rawSource.match.every(item=>typeof item=="string"))return fail("pages set","PAGE_SOURCE_INVALID",`Labels source "${name}" requires a non-empty match array.`);let invalidPattern=rawSource.match.find(pattern=>!isLabelPattern(pattern));if(invalidPattern)return fail("pages set","PAGE_LABEL_PATTERN_INVALID",`Label pattern "${invalidPattern}" must be an exact key or a literal prefix ending with ".*".`);sources[name]={type:"labels",match:[...new Set(rawSource.match)]};continue}if(rawSource.type==="single"){if(typeof rawSource.schema!="string"||!rawSource.schema)return fail("pages set","PAGE_SOURCE_INVALID",`Single source "${name}" requires a schema.`);sources[name]={type:"single",schema:rawSource.schema};continue}if(rawSource.type!=="collection"||typeof rawSource.schema!="string"||!rawSource.schema)return fail("pages set","PAGE_SOURCE_INVALID",`Source "${name}" must be labels, single, or collection.`);let query=rawSource.query===void 0?void 0:parseCollectionQuery(rawSource.query,`Collection source "${name}"`);sources[name]={type:"collection",schema:rawSource.schema,...query?{query}:{}}}return sources}__name(parseSources,"parseSources");function queryFields2(query){if(!query)return[];let fields=new Set;for(let field of Object.keys(query.where??{}))field.startsWith("$")||fields.add(field.split(".")[0]);for(let sort of fieldList2(query.sort))fields.add(sort.replace(/^-/,"").split(".")[0]);for(let field of[...fieldList2(query.fields),...fieldList2(query.populate)])fields.add(field.split(".")[0]);return[...fields]}__name(queryFields2,"queryFields");function entryFields(schema){return new Set([...Object.keys(schema.fields??{}),"id","slug"])}__name(entryFields,"entryFields");async function assertParamExpressions(query,subject,available,getSchema){for(let expression of pageSourceParamExpressions(query)){let parsed=parsePageParamExpression(expression);parsed||fail("pages set","PAGE_PARAM_EXPRESSION_INVALID",`Expression "${expression}" must use $params.<param>.<field>.`);let binding=Object.hasOwn(available,parsed.param)?available[parsed.param]:void 0;binding||fail("pages set","PAGE_PARAM_UNKNOWN",`${subject} references param "${parsed.param}", which this page does not bind before it.`),isEntryParamBinding(binding)||fail("pages set","PAGE_PARAM_KIND_INVALID",`${subject} references param "${parsed.param}", which is not a Collection entry param.`);let boundSchema=await getSchema(binding.schema),field=parsed.field.split(".")[0];(!boundSchema||!entryFields(boundSchema).has(field))&&fail("pages set","PAGE_PARAM_FIELD_UNKNOWN",`Field "${field}" does not exist on bound schema "${binding.schema}" (${expression}).`)}}__name(assertParamExpressions,"assertParamExpressions");function uniqueSourceName(sources,preferred){if(!sources[preferred])return preferred;let suffix=2;for(;sources[`${preferred}-${suffix}`];)suffix+=1;return`${preferred}-${suffix}`}__name(uniqueSourceName,"uniqueSourceName");function normalizedPageSources(route){let sources={...route.sources??{}},labels2=(route.content?.labels??[]).filter(isLabelPattern);labels2.length>0&&!Object.values(sources).some(source=>source.type==="labels")&&(sources[uniqueSourceName(sources,"labels")]={type:"labels",match:[...new Set(labels2)]});for(let schema of route.content?.singles??[]){if(!schema||Object.values(sources).some(source=>source.type==="single"&&source.schema===schema))continue;let preferred=`single-${schema}`;sources[uniqueSourceName(sources,preferred)]={type:"single",schema}}return sources}__name(normalizedPageSources,"normalizedPageSources");async function pagesListCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),{config,routes}=readPageRegistry(cwd,"pages list"),templates=Object.entries(routes).filter(entry=>typeof entry[1]?.path=="string").map(([id,route])=>{let sources=normalizedPageSources(route);return{id,path:route.path,label:route.label??route.path,status:pageStatus(route),...route.params?{params:route.params}:{},...Object.keys(sources).length>0?{sources}:{}}});if(!options.expand){ui.result({command:"pages list",data:{pages:templates},render:__name(()=>templates.length===0?"No pages are registered yet. Add one with `fimo pages set <id> --path <path>`.":templates.map(page=>`${page.status.padEnd(15)} ${page.path} (id ${page.id})`).join(`
|
|
918
|
+
`),"render")});return}let{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let i18n=config.i18n,defaultLocale=i18n?.defaultLocale??i18n?.locales?.[0]??"en",instances=[],skipped=[];for(let page of templates){let routePath=substituteLocaleParams(page.path,defaultLocale),contentParams=pageContentParamNames(routePath);if(contentParams.length===0){instances.push({id:page.id,path:routePath});continue}if(page.status==="dynamic:external"){let external=contentParams.filter(param=>!isEntryParamBinding(page.params?.[param]));skipped.push({id:page.id,path:page.path,reason:`values for ${external.map(param=>`":${param}"`).join(", ")} are owned by the application`});continue}if(page.status!=="dynamic:bound"){skipped.push({id:page.id,path:page.path,reason:"no schema binding; bind it with `fimo pages set`"});continue}let materialized=[{path:routePath,params:{}}],failedReason;for(let param of contentParams){let binding=page.params?.[param];if(!isEntryParamBinding(binding)){failedReason=`no binding for "${param}"`;break}let expanded=[],failExpansionLimit=__name(()=>fail("pages list","PAGE_EXPANSION_LIMIT_EXCEEDED",`Page "${page.id}" expands beyond ${MAX_EXPANDED_PAGE_INSTANCES.toLocaleString()} instances. Narrow its param queries with where or limit before using --expand.`),"failExpansionLimit");for(let candidate of materialized){let resolution=resolvePageSourceQuery(binding.query,candidate.params);if(!resolution.ok)continue;let rows=await fetchEntries(content2,ctx.projectId,binding.schema,resolution.query,binding.queryField,MAX_EXPANDED_PAGE_INSTANCES-expanded.length,failExpansionLimit);for(let row2 of rows){let value=entryFieldValue(row2,binding.queryField);value==null||value===""||(expanded.length>=MAX_EXPANDED_PAGE_INSTANCES&&failExpansionLimit(),expanded.push({path:substituteRouteParam(candidate.path,param,String(value)),params:{...candidate.params,[param]:row2}}))}}if(expanded.length===0){failedReason=`no ${binding.schema} entries to materialize`;break}materialized=expanded}if(failedReason){skipped.push({id:page.id,path:page.path,reason:failedReason});continue}instances.push(...materialized.map(instance=>({id:page.id,path:instance.path,from:Object.values(page.params??{}).filter(isEntryParamBinding).map(binding=>`${binding.schema}.${binding.queryField}`).join(", ")})))}ui.result({command:"pages list",data:{pages:templates,instances,skipped},render:__name(()=>[...instances.map(instance=>`${instance.path}${instance.from?` (${instance.id} \u2190 ${instance.from})`:""}`),...skipped.map(entry=>`SKIPPED ${entry.path}: ${entry.reason}`),`${instances.length} page instance(s) from ${templates.length} template(s)`].join(`
|
|
919
|
+
`),"render")})}__name(pagesListCommand,"pagesListCommand");function parseParams(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(!parsed||typeof parsed!="object"||Array.isArray(parsed)||Object.keys(parsed).length===0)return null;for(let[param,value]of Object.entries(parsed)){if(!isObject(value))return null;if(value.type==="external"){if(Object.keys(value).length!==1)return null;continue}if(value.type==="locale"){if(Object.keys(value).some(key=>key!=="type"&&key!=="optional")||value.optional!==void 0&&typeof value.optional!="boolean")return null;continue}if(value.type!==void 0&&value.type!=="entry"||Object.keys(value).some(key=>!ENTRY_PARAM_KEYS.has(key)))return null;for(let key of PAGE_PARAM_KEYS)if(typeof value[key]!="string"||!value[key])return null;value.query!==void 0&&parseCollectionQuery(value.query,`Param "${param}"`)}return parsed}__name(parseParams,"parseParams");async function pagesSetCommand(id,options,cmd){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages set");options.path!==void 0||options.label!==void 0||options.group!==void 0||options.sources!==void 0||options.clearSources===!0||options.icon!==void 0||options.params!==void 0||options.clearParams===!0||(ui.error({command:"pages set",code:"PAGE_SET_EMPTY",message:"Nothing to set. Pass --path, --label, --group, --sources, --clear-sources, --icon, --params, and/or --clear-params."}),process.exit(1)),options.sources!==void 0&&options.clearSources&&fail("pages set","PAGE_SOURCES_CONFLICT","Pass either --sources or --clear-sources, not both."),options.params!==void 0&&options.clearParams&&fail("pages set","PAGE_PARAMS_CONFLICT","Pass either --params or --clear-params, not both."),options.icon!==void 0&&options.icon!==""&&!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options.icon)&&(ui.error({command:"pages set",code:"PAGE_ICON_INVALID",message:'Icons use kebab-case Lucide names, for example "newspaper". Pass an empty value to clear it.'}),process.exit(1));let existing=routes[id];!existing&&!options.path&&(ui.error({command:"pages set",code:"PAGE_NOT_FOUND",message:`No page "${id}" exists in the registry. Creating one requires --path.`}),process.exit(1)),options.path!==void 0&&(!options.path.startsWith("/")||/[[\]]/.test(options.path))&&(ui.error({command:"pages set",code:"PAGE_PATH_INVALID",message:'Page paths start with "/" and use :param syntax, never [param].'}),process.exit(1));let next={...existing??{}};if(existing?.content){let normalizedSources=normalizedPageSources(existing);Object.keys(normalizedSources).length>0&&(next.sources=normalizedSources),delete next.content}if(options.path!==void 0&&(next.path=options.path),options.label!==void 0&&(options.label===""?delete next.label:next.label=options.label),options.group!==void 0&&(options.group===""?delete next.group:next.group=options.group),options.icon!==void 0&&(options.icon===""?delete next.icon:next.icon=options.icon),options.sources!==void 0&&(next.sources=parseSources(options.sources)),options.clearSources&&delete next.sources,options.params!==void 0){let params=parseParams(options.params)??void 0;params||(ui.error({command:"pages set",code:"PAGE_PARAMS_INVALID",message:'Expected {"<param>":{"schema":"<Type>","queryField":"<field>","displayField":"<field>"}} for a Collection entry, or {"<param>":{"type":"external"}} when the application owns the values.'}),process.exit(1)),next.params=params}if(options.clearParams&&delete next.params,options.path!==void 0&&options.params===void 0&&!options.clearParams&&next.params){let bindableParams=new Set(pageRouteParamNames(next.path??"")),retainedParams=Object.fromEntries(Object.entries(next.params).filter(([param])=>bindableParams.has(param)));Object.keys(retainedParams).length>0?next.params=retainedParams:delete next.params}let projectContextPromise,schemas3=new Map,getSchema=__name(async schemaName=>{if(schemas3.has(schemaName))return schemas3.get(schemaName)??null;projectContextPromise??=bootstrapProjectCommand(options,cmd);let{ctx,fimo}=await projectContextPromise;await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let schema;try{schema=await fimo.execute("schemas.get",{projectId:ctx.projectId,branch:ctx.branch,typeName:schemaName})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==404)throw error;schema=null}return schemas3.set(schemaName,schema),schema},"getSchema"),effectivePath=next.path??"",placeholders=pageRouteParamNames(effectivePath),contentParams=pageContentParamNames(effectivePath),effectiveParams=next.params??{};for(let[param,binding]of Object.entries(effectiveParams)){if((binding.type==="locale"?placeholders.includes(param)&&!contentParams.includes(param):contentParams.includes(param))||fail("pages set","PAGE_PARAM_UNKNOWN",binding.type==="locale"?`Param "${param}" is not the locale placeholder of the page path "${effectivePath}".`:placeholders.includes(param)?`Param "${param}" is the locale placeholder of the page path "${effectivePath}", not a content one.`:`Param "${param}" does not exist in the page path "${effectivePath}".`),!isEntryParamBinding(binding))continue;let schema=await getSchema(binding.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${binding.schema}" does not exist (param "${param}").`),schema.isSingleton!==!1&&fail("pages set","PAGE_PARAM_KIND_INVALID",`Param "${param}" needs a known Collection schema, but "${binding.schema}" is not marked as a Collection.`);let fields=entryFields(schema);for(let key of["queryField","displayField"])fields.has(binding[key])||fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${binding[key]}" does not exist on "${binding.schema}".`);if(!["id","slug"].includes(binding.queryField)){let definition=schema.fields?.[binding.queryField];(!isObject(definition)||definition.required!==!0)&&fail("pages set","PAGE_QUERY_FIELD_OPTIONAL",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "required": true.`),definition.unique!==!0&&fail("pages set","PAGE_QUERY_FIELD_NOT_UNIQUE",`Custom URL field "${binding.queryField}" on "${binding.schema}" must set "unique": true.`)}if(!binding.query)continue;let queryableFields2=new Set([...fields,"createdAt","updatedAt"]),unknownField=queryFields2(binding.query).find(field=>!queryableFields2.has(field));unknownField&&fail("pages set","PAGE_FIELD_UNKNOWN",`Field "${unknownField}" does not exist on "${binding.schema}".`);let selectedBefore=Object.fromEntries(contentParams.slice(0,contentParams.indexOf(param)).flatMap(earlier=>effectiveParams[earlier]?[[earlier,effectiveParams[earlier]]]:[]));await assertParamExpressions(binding.query,`Param "${param}"`,selectedBefore,getSchema)}for(let[sourceName,source]of Object.entries(next.sources??{})){if(source.type==="labels")continue;let schema=await getSchema(source.schema);schema||fail("pages set","PAGE_SCHEMA_UNKNOWN",`Schema "${source.schema}" does not exist (source "${sourceName}").`),source.type==="single"&&schema.isSingleton!==!0&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Single, but "${source.schema}" is not marked as a Single.`),source.type==="collection"&&schema.isSingleton!==!1&&fail("pages set","PAGE_SOURCE_KIND_INVALID",`Source "${sourceName}" expects a known Collection, but "${source.schema}" is not marked as a Collection.`);let query=source.type==="collection"?source.query:void 0,fields=new Set([...entryFields(schema),"createdAt","updatedAt"]),unknownSourceField=queryFields2(query).find(field=>!fields.has(field));unknownSourceField&&fail("pages set","PAGE_SOURCE_FIELD_UNKNOWN",`Field "${unknownSourceField}" does not exist on "${source.schema}" (source "${sourceName}").`),await assertParamExpressions(query,`Source "${sourceName}"`,effectiveParams,getSchema)}routes[id]=next,writePageRegistry(file,config,routes),ui.result({command:"pages set",data:{id,page:next},render:__name(()=>`Page "${id}" now points to ${next.path}.`,"render")})}__name(pagesSetCommand,"pagesSetCommand");function pagesDeleteCommand(id,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages delete");routes[id]||fail("pages delete","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),delete routes[id],writePageRegistry(file,config,routes),ui.result({command:"pages delete",data:{id},render:__name(()=>`Deleted page "${id}" from the registry.`,"render")})}__name(pagesDeleteCommand,"pagesDeleteCommand");function pagesRenameCommand(id,nextId,options){let cwd=resolveProjectCwd(options.cwd),{config,routes,file}=readPageRegistry(cwd,"pages rename");routes[id]||fail("pages rename","PAGE_NOT_FOUND",`No page "${id}" exists in the registry.`),id!==nextId&&routes[nextId]&&fail("pages rename","PAGE_ALREADY_EXISTS",`Page "${nextId}" already exists in the registry.`);let renamed=Object.fromEntries(Object.entries(routes).map(([routeId,route])=>[routeId===id?nextId:routeId,route]));writePageRegistry(file,config,renamed),ui.result({command:"pages rename",data:{id:nextId,previousId:id},render:__name(()=>`Renamed page "${id}" to "${nextId}".`,"render")})}__name(pagesRenameCommand,"pagesRenameCommand");init_esm();init_dist();init_config();init_project_services();init_project_context();var WAIT_TIMEOUT_MS=300*1e3,FIRST_POLL_MS=2e3,MAX_POLL_MS=15e3,POLL_GROWTH=1.5,PreviewUrlError=class extends Error{constructor(failure){super(failure.message);this.failure=failure;this.name="PreviewUrlError"}static{__name(this,"PreviewUrlError")}};function noHostedPreview(branch){return isProductionBranch(branch)?{message:`Branch '${branch}' is production and has no hosted preview.`,hint:"Publish with `fimo deploy --publish` and open the live site instead."}:{message:`Branch '${branch}' has no hosted preview yet.`,hint:"Run `fimo deploy` to push a change; that is what asks for a hosted preview."}}__name(noHostedPreview,"noHostedPreview");function errorMessage3(error){return error instanceof Error?error.message:String(error)}__name(errorMessage3,"errorMessage");async function previewUrlCommand(options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.preview.url",{projectId:ctx.projectId,branch:ctx.branch});let studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,ctx.branch);try{let sandbox=createSandboxService(loadConfig(),ctx.branch),deadline=Date.now()+WAIT_TIMEOUT_MS,delayMs=FIRST_POLL_MS,hosted=await sandbox.getHostedPreview(ctx.projectId,ctx.branch);for(;;){if(hosted===null)throw new PreviewUrlError(noHostedPreview(ctx.branch));if(hosted.status==="ready")break;if(hosted.status==="failed")throw new PreviewUrlError({message:"The hosted preview build failed.",hint:"Fix the project, then run `fimo deploy` to build the Branch again."});if(Date.now()+delayMs>=deadline)throw new PreviewUrlError({message:hosted.status==="queued"?"The hosted preview is still waiting to build.":"The hosted preview is still building.",hint:`Try \`fimo preview url\` again in a moment, or watch the Branch in Fimo: ${studioUrl}`});await new Promise(resolve10=>setTimeout(resolve10,delayMs)),delayMs=Math.min(Math.round(delayMs*POLL_GROWTH),MAX_POLL_MS),hosted=await sandbox.getHostedPreview(ctx.projectId,ctx.branch)}let url=hosted.url;if(!url)throw new PreviewUrlError({message:"The hosted preview is ready but did not return a URL.",hint:`Open the Branch in Fimo: ${studioUrl}`});ui.result({command:"preview url",data:{project_id:ctx.projectId,branch:ctx.branch,env:ctx.branch,preview_url:url},render:__name(context=>terminalLink("Open preview",url,context.hyperlinks),"render")})}catch(error){ui.error({command:"preview url",code:"PREVIEW_URL_FAILED",message:`Failed to get preview URL: ${errorMessage3(error)}`,hint:error instanceof PreviewUrlError?error.failure.hint:`Open the Branch in Fimo while it builds: ${studioUrl}`})}}__name(previewUrlCommand,"previewUrlCommand");function registerPreviewCommands(program2){program2.command("preview").description("Inspect a Branch preview without deploying").command("url").description("Get the hosted preview URL for the current Branch (or --branch <name>) without deploying").option("-C, --cwd <dir>","Run against this directory instead of cwd").action((opts,cmd)=>previewUrlCommand(opts,cmd))}__name(registerPreviewCommands,"registerPreviewCommands");init_esm();init_dist();init_config();init_sdk_transport();import fs43 from"node:fs";import path45 from"node:path";function mergeManagedEnvBlock(existing,entries2,spec){let block=renderBlock(entries2,spec),normalized=existing.replace(/\r\n/g,`
|
|
920
920
|
`),lines=normalized.endsWith(`
|
|
921
921
|
`)?normalized.slice(0,-1).split(`
|
|
922
922
|
`):normalized.split(`
|
|
@@ -964,7 +964,7 @@ Output
|
|
|
964
964
|
${run.output}`:fields},"render")})}__name(renderRunDetail,"renderRunDetail");function renderFields(fields){let width=Math.max(...Object.keys(fields).map(key=>key.length));return Object.entries(fields).map(([key,value])=>`${key.padEnd(width)} ${String(value)}`).join(`
|
|
965
965
|
`)}__name(renderFields,"renderFields");function renderTable(headers,rows){if(rows.length===0)return"No results.";let widths=headers.map((header,index)=>Math.max(header.length,...rows.map(row2=>String(row2[index]??"").length)));return[headers,...rows].map(row2=>row2.map((value,index)=>String(value).padEnd(widths[index])).join(" ").trimEnd()).join(`
|
|
966
966
|
`)}__name(renderTable,"renderTable");function readActiveRunId(body){if(!body||typeof body!="object")return;let value=body.activeRunId;return typeof value=="string"?value:void 0}__name(readActiveRunId,"readActiveRunId");init_esm();init_dist();import fs46 from"node:fs";import path47 from"node:path";import{isDeepStrictEqual}from"node:util";init_sdk_transport();init_project_context();init_project();var SYSTEM_SCHEMA_FIELDS=new Set(RESERVED_CONTENT_FIELD_NAMES),SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message,options){super(message,options),this.name="SchemaCommandError",this.code=code2}};function isRecord3(value){return!!(value&&typeof value=="object"&&!Array.isArray(value))}__name(isRecord3,"isRecord");function schemaMatches(actual,expected){if(!isRecord3(actual)||!isRecord3(actual.fields))return!1;let userFields=Object.fromEntries(Object.entries(actual.fields).filter(([fieldName])=>!SYSTEM_SCHEMA_FIELDS.has(fieldName)));return actual.name===expected.name&&actual.label===expected.label&&actual.isSingleton===expected.isSingleton&&isDeepStrictEqual(actual.i18n,expected.i18n)&&isDeepStrictEqual(actual.groups??[],expected.groups)&&isDeepStrictEqual(userFields,expected.fields)}__name(schemaMatches,"schemaMatches");async function readBackSchemaBatch(fimo,projectId,branch,schemas3){let checks=await Promise.all(schemas3.map(async schema=>{try{let actual=await fimo.execute("schemas.get",{projectId,branch,typeName:schema.name});return{name:schema.name,actual,state:schemaMatches(actual,schema)?"matched":"mismatched"}}catch(error){if(error instanceof ApiRequestError&&error.status===404)return{name:schema.name,state:"absent"};throw error}})),matched=checks.filter(check=>check.state==="matched"),absent=checks.filter(check=>check.state==="absent"),mismatched=checks.filter(check=>check.state==="mismatched");return matched.length===schemas3.length?{state:"committed",results:matched.map(check=>check.actual)}:absent.length===schemas3.length?{state:"absent"}:{state:"ambiguous",details:[matched.length>0?`matched: ${matched.map(check=>check.name).join(", ")}`:null,absent.length>0?`absent: ${absent.map(check=>check.name).join(", ")}`:null,mismatched.length>0?`mismatched: ${mismatched.map(check=>check.name).join(", ")}`:null].filter(Boolean).join("; ")}}__name(readBackSchemaBatch,"readBackSchemaBatch");async function upsertSchemasWithReconciliation(fimo,projectId,branch,schemas3,operations){let timeout;try{return await fimo.execute("schemas.upsertBatch",{projectId,branch,contentTypes:schemas3,operations:[...operations]})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let firstReadBack=await readBackAfterTimeout(fimo,projectId,branch,schemas3,timeout);if(firstReadBack.state==="committed")return firstReadBack.results;if(firstReadBack.state==="ambiguous")throw ambiguousSchemaPushError(firstReadBack.details,timeout);try{return await fimo.execute("schemas.upsertBatch",{projectId,branch,contentTypes:schemas3,operations:[...operations]})}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let secondReadBack=await readBackAfterTimeout(fimo,projectId,branch,schemas3,timeout);if(secondReadBack.state==="committed")return secondReadBack.results;let detail=secondReadBack.state==="absent"?"all requested schemas remain absent after one retry":secondReadBack.details;throw ambiguousSchemaPushError(detail,timeout)}__name(upsertSchemasWithReconciliation,"upsertSchemasWithReconciliation");function ambiguousSchemaPushError(detail,cause){return new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 (${detail}). No further write was attempted; read the schemas back before rerunning.`,{cause})}__name(ambiguousSchemaPushError,"ambiguousSchemaPushError");async function readBackAfterTimeout(fimo,projectId,branch,schemas3,timeout){try{return await readBackSchemaBatch(fimo,projectId,branch,schemas3)}catch(error){let detail=error instanceof Error?error.message:String(error);throw new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 and read-back failed (${detail}). No retry was attempted.`,{cause:timeout})}}__name(readBackAfterTimeout,"readBackAfterTimeout");function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},groups:schema.groups??[],fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson8,"renderPrettyJson");function isUniqueConflictIssue(issue){if(!issue||typeof issue!="object"||Array.isArray(issue))return!1;let candidate=issue;return candidate.kind==="unique_conflict"&&typeof candidate.contentType=="string"&&typeof candidate.field=="string"&&typeof candidate.value=="string"&&typeof candidate.documentCount=="number"&&Array.isArray(candidate.documentIds)&&candidate.documentIds.every(id=>typeof id=="string")&&(candidate.documentIdsTruncated===void 0||typeof candidate.documentIdsTruncated=="boolean")}__name(isUniqueConflictIssue,"isUniqueConflictIssue");function getUniqueConflictIssues(body){if(!body||typeof body!="object"||Array.isArray(body))return null;let issues=body.issues;return Array.isArray(issues)?issues.filter(isUniqueConflictIssue):null}__name(getUniqueConflictIssues,"getUniqueConflictIssues");function renderSchemaTransitionRejected(body,issues){currentMode().format==="json"?ui.result({command:"schemas push",data:body,render:__name(()=>"","render")}):ui.table({command:"schemas push",headline:"Schema push rejected. Nothing was written.",columns:[{key:"content_type",label:"CONTENT TYPE"},{key:"field",label:"FIELD"},{key:"value",label:"VALUE"},{key:"documents",label:"DOCUMENTS"},{key:"document_ids",label:"DOCUMENT IDS"}],rows:issues.map(issue=>{let remaining=Math.max(issue.documentCount-issue.documentIds.length,0),truncationNote=remaining>0?`... and ${remaining} more`:"... and more";return{content_type:issue.contentType,field:issue.field,value:issue.value,documents:issue.documentCount,document_ids:issue.documentIdsTruncated?[...issue.documentIds,truncationNote].join(", "):issue.documentIds.join(", ")}})}),process.exitCode=1}__name(renderSchemaTransitionRejected,"renderSchemaTransitionRejected");async function schemaListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.list",{projectId:ctx.projectId,branch:ctx.branch});ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.get",{projectId:ctx.projectId,branch:ctx.branch,typeName});ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),schemasDir=path47.join(cwd,"src/schemas"),allSchemaFiles=fs46.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs46.readFileSync(path47.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files.map(file=>{let filePath=path47.join(schemasDir,file);if(!fs46.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path47.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue=>`${issue.file}: ${issue.message}`).join(`
|
|
967
|
-
`));return JSON.parse(fs46.readFileSync(filePath,"utf-8"))}),framework=await detectProjectFramework(cwd);syncSchemas({cwd,framework:framework?.slug??null,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await upsertSchemasWithReconciliation(fimo,ctx.projectId,ctx.branch,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.deleteFromBranch",{projectId:ctx.projectId,branch:ctx.branch,typeName});ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_dist();init_project_context();var SinglesInputError=class extends Error{static{__name(this,"SinglesInputError")}constructor(message){super(message),this.name="SinglesInputError"}};function renderPrettyJson9(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson9,"renderPrettyJson");function parseJsonObject2(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new SinglesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new SinglesInputError("Expected a JSON object.");return parsed}__name(parseJsonObject2,"parseJsonObject");async function singlesGetCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("singles.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,populate:options.populate?[options.populate]:void 0});ui.result({command:"singles get",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesGetCommand,"singlesGetCommand");async function singlesUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let input=parseJsonObject2(await readContentInputSource(options,message=>new SinglesInputError(message))),{data:result}=await fimo.execute("singles.update",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,data:input.data});ui.result({command:"singles update",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesUpdateCommand,"singlesUpdateCommand");init_status();import{readFileSync as
|
|
967
|
+
`));return JSON.parse(fs46.readFileSync(filePath,"utf-8"))}),framework=await detectProjectFramework(cwd);syncSchemas({cwd,framework:framework?.slug??null,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await upsertSchemasWithReconciliation(fimo,ctx.projectId,ctx.branch,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("schemas.deleteFromBranch",{projectId:ctx.projectId,branch:ctx.branch,typeName});ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_dist();init_project_context();var SinglesInputError=class extends Error{static{__name(this,"SinglesInputError")}constructor(message){super(message),this.name="SinglesInputError"}};function renderPrettyJson9(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson9,"renderPrettyJson");function parseJsonObject2(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new SinglesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new SinglesInputError("Expected a JSON object.");return parsed}__name(parseJsonObject2,"parseJsonObject");async function singlesGetCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("singles.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,populate:options.populate?[options.populate]:void 0});ui.result({command:"singles get",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesGetCommand,"singlesGetCommand");async function singlesUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let input=parseJsonObject2(await readContentInputSource(options,message=>new SinglesInputError(message))),{data:result}=await fimo.execute("singles.update",{projectId:ctx.projectId,branch:ctx.branch,typeName,locale:options.locale,data:input.data});ui.result({command:"singles update",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesUpdateCommand,"singlesUpdateCommand");init_status();import{readFileSync as readFileSync12}from"node:fs";import path48 from"node:path";init_dist();init_config();init_sdk_transport();init_project_services();init_project_context();init_version();var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with project and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Project directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addOption(new Option("--source <origin>","Origin of the report").choices(["agent"]).hideHelp()).addHelpText("after",`
|
|
968
968
|
Examples:
|
|
969
969
|
fimo support report "Preview deployment fails after validation"
|
|
970
970
|
fimo support report --message-file /tmp/fimo-support-report.md --preview --json
|
|
@@ -973,7 +973,7 @@ Examples:
|
|
|
973
973
|
`).action((message,options,command)=>supportReportCommand(message??[],options,command))}__name(registerSupportCommands,"registerSupportCommands");async function supportReportCommand(messageParts,options,command){let message=resolveSupportMessage(messageParts,options.messageFile);if(message===null)return;let cfg=loadConfig(),fimo=createCliFimoClient(cfg),support=createSupportService(cfg),projectContext=await getProjectContext({cwd:options.cwd,branchOverride:branchOverrideFromCommand(command)});try{let[{data:project},{data:organizations}]=await Promise.all([fimo.execute("projects.get",{projectId:projectContext.projectId}),fimo.execute("organizations.list",{})]),organizationId=project.organizationId??projectContext.organizationId,organization=organizations.find(candidate=>candidate.id===organizationId),reportContext={message,projectId:project.id,projectName:project.displayName??project.name,organizationId,organizationName:organization?.name??organizationId,environment:projectContext.branch,cliVersion:getCliVersion()},submittedMessage=buildSupportMessage(reportContext);if(submittedMessage.length>MAX_SUPPORT_MESSAGE_LENGTH){ui.error({command:"support report",code:"SUPPORT_MESSAGE_TOO_LONG",message:`The complete report is ${submittedMessage.length.toLocaleString()} characters; the limit is ${MAX_SUPPORT_MESSAGE_LENGTH.toLocaleString()}.`,hint:"Keep the observed failure or capability gap, impact, and workaround; remove raw logs and unrelated context."});return}if(options.preview){ui.result({command:"support report",data:{submitted:!1,message:submittedMessage,project_id:reportContext.projectId,project_name:reportContext.projectName,environment:reportContext.environment},render:__name(()=>submittedMessage,"render")});return}if(!options.yes){assertInteractive("Review the report, then pass --yes to send it without prompting.","support report"),wt(submittedMessage,"Report preview");let confirmed=await ot2({message:"Send this report to Fimo support?",initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"support report",message:"Cancelled."});return}}let result=await support.submit({message:submittedMessage,category:"project_issues",source:options.source??"cli",context:{organization:{id:reportContext.organizationId,name:reportContext.organizationName},project:{id:reportContext.projectId,name:reportContext.projectName,createdAt:new Date(project.createdAt)},environment:reportContext.environment,clientVersion:reportContext.cliVersion}});ui.result({command:"support report",data:{submitted:!0,project_id:reportContext.projectId,project_name:reportContext.projectName,environment:reportContext.environment,report_id:result.id,delivery_status:result.deliveryStatus},render:__name(()=>`${result.message}
|
|
974
974
|
Report: ${result.id}
|
|
975
975
|
Project: ${reportContext.projectName}
|
|
976
|
-
Environment: ${reportContext.environment}`,"render")})}catch(error){rethrowCliAuthError(error),ui.error({command:"support report",code:"SUPPORT_REPORT_FAILED",message:error instanceof Error?error.message:"The support report could not be sent.",hint:"Try again later, or contact Fimo support through the app."})}}__name(supportReportCommand,"supportReportCommand");function resolveSupportMessage(messageParts,messageFile){if(messageParts.length>0&&messageFile)return ui.error({command:"support report",code:"SUPPORT_MESSAGE_CONFLICT",message:"Pass the report as text or with --message-file, not both."}),null;let message=messageParts.join(" ").trim();if(messageFile)try{message=
|
|
976
|
+
Environment: ${reportContext.environment}`,"render")})}catch(error){rethrowCliAuthError(error),ui.error({command:"support report",code:"SUPPORT_REPORT_FAILED",message:error instanceof Error?error.message:"The support report could not be sent.",hint:"Try again later, or contact Fimo support through the app."})}}__name(supportReportCommand,"supportReportCommand");function resolveSupportMessage(messageParts,messageFile){if(messageParts.length>0&&messageFile)return ui.error({command:"support report",code:"SUPPORT_MESSAGE_CONFLICT",message:"Pass the report as text or with --message-file, not both."}),null;let message=messageParts.join(" ").trim();if(messageFile)try{message=readFileSync12(path48.resolve(messageFile),"utf8").trim()}catch(error){return ui.error({command:"support report",code:"SUPPORT_MESSAGE_READ_FAILED",message:error instanceof Error?error.message:"The report file could not be read."}),null}return message||(ui.error({command:"support report",code:"SUPPORT_MESSAGE_REQUIRED",message:"Describe what went wrong or which capability is missing, or pass --message-file <path>."}),null)}__name(resolveSupportMessage,"resolveSupportMessage");function buildSupportMessage(context){return[context.message,"","Fimo CLI context",`Project: ${context.projectName} (${context.projectId})`,`Environment: ${context.environment}`,`Fimo CLI: ${context.cliVersion}`].join(`
|
|
977
977
|
`)}__name(buildSupportMessage,"buildSupportMessage");init_dist();init_auth();init_config();init_sdk_transport();async function switchCommand(options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),fimo=createCliFimoClient(cfg),{data:orgs2}=await fimo.execute("organizations.list",{});if(orgs2.length===0){ui.error({command:"orgs switch",code:"NO_ORGANIZATIONS",message:"No organization found for this account."});return}if(options.org){let target2=orgs2.find(org=>org.id===options.org)??orgs2.find(org=>org.slug===options.org);if(!target2){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:`No organization matched "${options.org}".`,hint:"Run `fimo orgs list` to see available orgs."});return}setActiveOrganization({id:target2.id,name:target2.name,slug:target2.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target2.name}`,details:{id:target2.id,name:target2.name,slug:target2.slug}});return}assertInteractive("Pass --org <id-or-slug>.","orgs switch"),mt("Switch active organization");let currentId=creds.activeOrganization?.id,selected=await _t({message:"Select an organization",initialValue:currentId,options:orgs2.map(org=>({value:org.id,label:org.name,hint:org.id===currentId?"current":org.slug}))});if(q(selected)){ui.info({command:"orgs switch",message:"Cancelled."});return}let target=orgs2.find(org=>org.id===selected);if(!target){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:"Selected organization not found."});return}setActiveOrganization({id:target.id,name:target.name,slug:target.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target.name}`,details:{id:target.id,name:target.name,slug:target.slug}})}__name(switchCommand,"switchCommand");import fs48 from"node:fs";import path50 from"node:path";init_dist();init_git();init_project();import fs47 from"node:fs";import path49 from"node:path";function expectedFimoPackages(framework,usesReact){switch(framework){case"react-router":return["fimo","fimo-react","fimo-vite","fimo-react-router"];case"vite":return usesReact?["fimo","fimo-react","fimo-vite","fimo-react-router"]:["fimo","fimo-vite"];case"nextjs":return["fimo","fimo-react","fimo-next"];case"astro":return["fimo","fimo-astro"];case"sveltekit":return["fimo","fimo-sveltekit"];default:return["fimo"]}}__name(expectedFimoPackages,"expectedFimoPackages");var RETIRED_IMPORT_MAPPINGS=[{from:"fimo/ui",to:"fimo-react"},{from:"fimo/next",to:"fimo-next"},{from:"fimo/next/client",to:"fimo-next/client"},{from:"fimo/next/config",to:"fimo-next/config"},{from:"fimo/react-router",to:"fimo-react-router"},{from:"fimo/react-router/routes",to:"fimo-react-router/routes"},{from:"fimo/react-router/preset",to:"fimo-react-router/preset"},{from:"fimo/sveltekit",to:"fimo-sveltekit"},{from:"fimo/sveltekit/components",to:"fimo-sveltekit/components"},{from:"fimo/sveltekit/internal",to:"fimo-sveltekit/internal"},{from:"fimo/sveltekit/vite",to:"fimo-sveltekit/vite"},{from:"fimo/sveltekit/config",to:"fimo-sveltekit/config"},{from:"fimo/vite",to:{react:"fimo-react-router/vite",default:"fimo-vite"}}],MANUAL_REVIEW_IMPORTS=[{specifier:"fimo/astro/config",note:'fimo/astro/config stays valid for the provider-neutral Studio integration; only Fimo hosting for Astro moved to fimo-astro/config. Review astro.config.* and switch to `import { fimo } from "fimo-astro/config"` only if the project deploys through Fimo.'}];function migrationNote(...lines){return lines.join(`
|
|
978
978
|
`)}__name(migrationNote,"migrationNote");var UPDATE_MIGRATIONS=[{version:"1.0.0",summary:"First stable release. The single fimo package splits into fimo plus per-framework companion packages, all released at the same version.",codemods:["retired-imports"],breakingChanges:[migrationNote("React components, React Router providers, and the Vite integration moved to framework packages. The update installs any missing packages before rewriting these imports.","","Before:","","```tsx","import { Label, Text } from 'fimo/ui';","import { FimoProviders } from 'fimo/react-router';","```","","After:","","```tsx","import { Label, Text } from 'fimo-react';","import { FimoProviders } from 'fimo-react-router';","```","","Update the Vite integration too:","","```ts","import { reactRouter } from '@react-router/dev/vite';","import { fimo } from 'fimo-react-router/vite';","import { defineConfig } from 'vite';","","export default defineConfig({"," plugins: [reactRouter(), fimo({ sitemap: true })],","});","```"),migrationNote("Next.js code moves from `fimo/next` to `fimo-next`. The update adds and installs `fimo-next` and `fimo-react` if they are missing, then rewrites the retired imports. Server and client imports remain separate.","","Before:","","```tsx","import { FimoProvider, getLabels } from 'fimo/next';","import { Text, useLabels } from 'fimo/next/client';","```","","After:","","```tsx","import { FimoProvider, getLabels } from 'fimo-next';","import { Text, useLabels } from 'fimo-next/client';","```","","Configure hosted previews through `fimo-next/config`:","","```ts","import type { NextConfig } from 'next';","import { withFimo } from 'fimo-next/config';","","const nextConfig: NextConfig = {};","","export default withFimo(nextConfig);","```"),migrationNote("Astro configuration depends on where the application is hosted, so the update reports `fimo/astro/config` for manual review instead of replacing it.","","For Fimo hosting or the Fimo server adapter:","","```js","import { fimo } from 'fimo-astro/config';","```","","For a static Astro project hosted elsewhere, keep:","","```js","import { fimo } from 'fimo/astro/config';","```","","Astro content APIs and components remain in `fimo`:","","```astro","---","import { getLabels } from 'fimo/astro';","import { Image, RichText, Text } from 'fimo/astro/components';","---","```"),migrationNote("SvelteKit integrations move from `fimo/sveltekit` to `fimo-sveltekit`. The update installs `fimo-sveltekit` if it is missing and rewrites the direct imports.","","Before:","","```ts","import { createFimo } from 'fimo/sveltekit';","import { fimo } from 'fimo/sveltekit/vite';","```","","After:","","```ts","import { createFimo } from 'fimo-sveltekit';","import { fimo } from 'fimo-sveltekit/vite';","```","","Update the root provider too:","","```svelte",'<script lang="ts">'," import { FimoProvider } from 'fimo-sveltekit/components';","</script>","```"),migrationNote("React Router projects using `fimo/react-router/routes` need a route-ownership migration after the compatibility import rewrite. Load the dedicated reference before changing the route configuration:","","```bash","npx fimo@latest skills get fimo-code --ref migrations/react-router-route-ownership","```")],improvements:[migrationNote("Framework code now has explicit import paths for each runtime:","","```ts","import { Text } from 'fimo-react'; // React components","import { getLabels } from 'fimo-next'; // Next.js server code","import { useLabels } from 'fimo-next/client'; // Next.js client code","import { createFimo } from 'fimo-sveltekit'; // SvelteKit server code","```"),"`fimo update` handles package additions and direct import rewrites. It leaves conditional migrations, including Astro hosting and React Router route ownership, as explicit manual steps."],recommendations:[migrationNote("Keep `fimo validate --json` at the beginning of the existing build command:","","```json","{",' "scripts": {',' "build": "fimo validate --json && vite build"'," }","}","```","","Preserve the framework build command. For example, use `next build` for Next.js and `astro build` for Astro."),migrationNote("Record the exact package-manager version and commit its lockfile:","","```json","{",' "packageManager": "pnpm@10.26.0"',"}","```"),migrationNote("Load the detected framework reference before completing manual changes, then run the project build:","","```bash","npx fimo@latest skills get fimo-code --ref frameworks/next","npx fimo@latest skills get fimo-code --ref frameworks/astro","npx fimo@latest skills get fimo-code --ref frameworks/sveltekit","npx fimo@latest skills get fimo-code --ref frameworks/react-router","npx fimo@latest skills get fimo-code --ref frameworks/vite-react","pnpm build","```")]},{version:"2.2.0",summary:"Media fields store asset references and load current asset facts only when a read requests them.",codemods:[],breakingChanges:[],improvements:[migrationNote("Media metadata is opt-in.","","Without `populate`:","","```ts","const article = await Article.getBySlug('hello');","// article.cover:","// { id?: string; url: string; alt?: string }","```","","Add `populate` when this read needs asset metadata:","","```ts","const article = await Article.getBySlug('hello', { populate: ['cover'] as const });","// article.cover:","// { id?: string; url: string; alt?: string; name?: string; mime?: string; width?: number; height?: number }","```","","Lists use the same option:","","```ts","const page = await Article.list({ populate: ['cover'] as const });","// page.items[0].cover has the populated shape above","```","","The fields marked `?` may be missing for external, missing, or incomplete assets."),migrationNote("Writes keep the reference and optional entry alt text:","","```ts","await Article.create({ cover: { id: 'asset_123', alt: 'Hero' } });","```","","Do not write asset metadata; Fimo reads it when you populate.")],recommendations:["Add `populate` only to reads that use current media metadata. Leave other reads unchanged."]}];function migrationsForTarget(target){return UPDATE_MIGRATIONS.filter(entry=>compareVersions(entry.version,target)<=0)}__name(migrationsForTarget,"migrationsForTarget");function updateGuidanceCommand(){return"npx fimo@latest skills get fimo-cli --ref update"}__name(updateGuidanceCommand,"updateGuidanceCommand");var EXACT_VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function compareVersions(a,b){let parse12=__name(value=>value.split("-")[0].split(".").map(Number),"parse"),[aMajor,aMinor,aPatch]=parse12(a),[bMajor,bMinor,bPatch]=parse12(b);return aMajor-bMajor||aMinor-bMinor||aPatch-bPatch}__name(compareVersions,"compareVersions");var OWNED_DIST_TAGS=new Set(["latest","staging","experimental"]);function classifyDepValue(value){return value.startsWith("file:")||/r2\.dev\/cli\//.test(value)||value.endsWith(".tgz")?"dev-pin":/^[\^~]?\d+\.\d+\.\d+/.test(value)||OWNED_DIST_TAGS.has(value)?"owned":"bespoke"}__name(classifyDepValue,"classifyDepValue");function planPackageChanges(pkg,target,expected){let changes=[],blockers=[],declared=new Set,fimoSection=null;for(let section2 of["dependencies","devDependencies"]){let deps=pkg[section2];if(deps)for(let name of FIMO_PACKAGES){let current=deps[name];if(typeof current!="string")continue;declared.add(name),name==="fimo"&&fimoSection===null&&(fimoSection=section2);let targetPin=deriveFimoPackagePin(name,target),kind=classifyDepValue(current);if(kind!=="owned"){let reason=kind==="dev-pin"?`"${current}" selects a development build; \`fimo update\` never replaces it. Publish and repin through the development channel, or set an exact version yourself first.`:`"${current}" is not a version this CLI manages; update it yourself first.`;changes.push({name,section:section2,from:current,to:null,action:"blocked",reason}),blockers.push({code:kind==="dev-pin"?"DEV_PIN":"BESPOKE_PIN",message:`${section2}.${name}: ${reason}`});continue}if(current===targetPin){changes.push({name,section:section2,from:current,to:current,action:"unchanged"});continue}changes.push({name,section:section2,from:current,to:targetPin,action:"update"})}}for(let name of expected)declared.has(name)||changes.push({name,section:fimoSection??"dependencies",from:null,to:deriveFimoPackagePin(name,target),action:"add"});return{changes,blockers}}__name(planPackageChanges,"planPackageChanges");function applyPackageChanges(pkg,changes){let changed=!1;for(let change of changes){if(change.action!=="update"&&change.action!=="add"||change.to===null)continue;let deps=pkg[change.section]??={};deps[change.name]!==change.to&&(deps[change.name]=change.to,changed=!0)}return changed}__name(applyPackageChanges,"applyPackageChanges");var KNOWN_FRAMEWORKS=["react-router","vite","astro","nextjs","sveltekit"],COMPANION_FRAMEWORKS=[["fimo-react-router","react-router"],["fimo-next","nextjs"],["fimo-sveltekit","sveltekit"],["fimo-astro","astro"],["fimo-vite","vite"]];function resolveUpdateFramework(detectedSlug,pkg){let deps={...pkg.dependencies,...pkg.devDependencies},has=__name(name=>typeof deps[name]=="string","has"),framework=KNOWN_FRAMEWORKS.find(slug=>slug===detectedSlug)??null;framework||(framework=COMPANION_FRAMEWORKS.find(([companion])=>has(companion))?.[1]??null);let usesReact=framework==="react-router"||framework==="nextjs"||has("react")||has("fimo-react");return{framework,usesReact,label:framework==="vite"?usesReact?"vite (react)":"vite":framework??"unknown"}}__name(resolveUpdateFramework,"resolveUpdateFramework");var SKIPPED_DIRECTORIES=new Set(["node_modules","dist","build","out","coverage","vendor"]),SOURCE_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".svelte",".astro",".vue",".mdx"]),MAX_FILE_BYTES=1024*1024;function escapeRegExp2(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp2,"escapeRegExp");function replacementFor(mapping,usesReact){return typeof mapping.to=="string"?mapping.to:usesReact?mapping.to.react:mapping.to.default}__name(replacementFor,"replacementFor");function listSourceFiles(root){let files=[],walk=__name(dir=>{let entries2;try{entries2=fs47.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(entry.isDirectory()){!entry.name.startsWith(".")&&!SKIPPED_DIRECTORIES.has(entry.name)&&walk(path49.join(dir,entry.name));continue}entry.isFile()&&SOURCE_EXTENSIONS.has(path49.extname(entry.name))&&files.push(path49.join(dir,entry.name))}},"walk");return walk(root),files.sort()}__name(listSourceFiles,"listSourceFiles");function runRetiredImportsCodemod(options){let{cwd,usesReact,write}=options,changedFiles=[],manualFollowUps=[],files=listSourceFiles(cwd),mappings=[...RETIRED_IMPORT_MAPPINGS].sort((a,b)=>b.from.length-a.from.length);for(let filePath of files){let source;try{if(fs47.statSync(filePath).size>MAX_FILE_BYTES)continue;source=fs47.readFileSync(filePath,"utf8")}catch{continue}if(!source.includes("fimo/"))continue;let relative3=path49.relative(cwd,filePath)||filePath,updated=source,replacements=[];for(let mapping of mappings){let to=replacementFor(mapping,usesReact),pattern=new RegExp(`(['"])${escapeRegExp2(mapping.from)}\\1`,"g"),count=0;updated=updated.replace(pattern,(_match,quote)=>(count+=1,`${quote}${to}${quote}`)),count>0&&replacements.push({from:mapping.from,to,count}),updated.includes(`\`${mapping.from}\``)&&manualFollowUps.push({file:relative3,specifier:mapping.from,note:`Found \`${mapping.from}\` in a template literal; replace it with \`${to}\` manually.`})}for(let manual of MANUAL_REVIEW_IMPORTS)new RegExp(`['"\`]${escapeRegExp2(manual.specifier)}['"\`]`).test(updated)&&manualFollowUps.push({file:relative3,specifier:manual.specifier,note:manual.note});replacements.length>0&&(changedFiles.push({file:relative3,replacements}),write&&fs47.writeFileSync(filePath,updated))}return{id:"retired-imports",filesScanned:files.length,changedFiles,manualFollowUps}}__name(runRetiredImportsCodemod,"runRetiredImportsCodemod");function renderMigrationGuidance(migration){return[migration.breakingChanges.length>0?`### Breaking changes
|
|
979
979
|
|
|
@@ -1005,10 +1005,10 @@ Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=lite
|
|
|
1005
1005
|
`);addScopeOptions5(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions5(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand5(opts,command)),addScopeOptions5(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions5(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect4).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id","main").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand4(name,opts,command)),addScopeOptions5(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect4).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand4(webhookId,opts,command)),addScopeOptions5(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand3(webhookId,opts,command)),addScopeOptions5(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions5(addPaginationOptions(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries"),{defaultLimit:50,maxLimit:100})).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions5(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions5(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions5(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope4(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,branch:ctx.branch}}return await requireOperation(op,scope),{...scope,fimo:createCliFimoClient(loadConfig())}}__name(resolveScope4,"resolveScope");async function eventsCommand(eventType,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.events",opts,command),events=await fimo.execute("webhooks.events",{projectId});if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand5(opts,command){let{fimo,projectId}=await resolveScope4("webhooks.list",opts,command),webhooks=await fimo.execute("webhooks.list",{projectId});ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand5,"listCommand");async function getCommand(webhookId,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.get",opts,command);renderJson("webhooks get",await fimo.execute("webhooks.get",{projectId,webhookId}))}__name(getCommand,"getCommand");async function createCommand4(name,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await fimo.execute("webhooks.create",{projectId,webhook:parsed.data});renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand4,"createCommand");async function updateCommand4(webhookId,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await fimo.execute("webhooks.get",{projectId,webhookId}),filter=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter?{filter}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await fimo.execute("webhooks.update",{projectId,webhookId,webhook:parsed.data}))}__name(updateCommand4,"updateCommand");async function deleteCommand3(webhookId,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.delete",opts,command);await fimo.execute("webhooks.delete",{projectId,webhookId}),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand3,"deleteCommand");async function testCommand(webhookId,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.test",opts,command),data=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await fimo.execute("webhooks.test",{projectId,webhookId,data});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await fimo.execute("webhooks.getDelivery",{projectId,webhookId,deliveryId:delivery.id})).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let pagination;try{pagination=parsePaginationOptions(opts,{defaultLimit:50,maxLimit:100}),pagination.cursor!==void 0&&parseCursorNumber(pagination.cursor,{defaultValue:1,minimum:1})}catch(error){throw error instanceof PaginationValidationError?new WebhookCommandError(error.kind==="invalid_limit"?"WEBHOOK_LIMIT_INVALID":"WEBHOOK_CURSOR_INVALID",error.message):error}let{fimo,projectId}=await resolveScope4("webhooks.deliveries.list",opts,command),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let pageNumber=parseCursorNumber(cursor,{defaultValue:1,minimum:1}),response=await fimo.execute("webhooks.listDeliveries",{projectId,webhookId,page:pageNumber,limit:pagination.limit});return{items:response.items,nextCursor:response.pagination.hasMore?String(response.pagination.page+1):null,total:response.pagination.total,pagination:response.pagination,stats:response.stats}},"fetchPage")}),trailingArgs=[];opts.project&&trailingArgs.push("--project",opts.project),opts.cwd&&trailingArgs.push("--cwd",opts.cwd);let rows=page.items.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)})),hint=page.nextCursor?buildPaginationHint(["fimo","webhooks","deliveries",webhookId],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs}):void 0;ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows,jsonData:{items:page.items,nextCursor:page.nextCursor,total:page.total,pagination:page.pagination,stats:page.stats},...hint?{hint}:{}})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await fimo.execute("webhooks.getDelivery",{projectId,webhookId,deliveryId}))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await fimo.execute("webhooks.retryDelivery",{projectId,webhookId,deliveryId}))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{fimo,projectId}=await resolveScope4("webhooks.rotate_secret",opts,command),signingSecret=await fimo.execute("webhooks.rotateSecret",{projectId,webhookId});renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path52=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile6(path52,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path52}'.`)}}return parseJson(input,flag2)}__name(parseJsonInput,"parseJsonInput");async function readStdin2(){let input="";process.stdin.setEncoding("utf8");for await(let chunk of process.stdin)input+=chunk;return input}__name(readStdin2,"readStdin");function parseJsonObject3(value,flag2){let parsed=parseJson(value,flag2);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new WebhookCommandError("WEBHOOK_DATA_INVALID",`${flag2} must be a JSON object.`);return parsed}__name(parseJsonObject3,"parseJsonObject");function parseOnOff(value,flag2){if(value==="on")return!0;if(value==="off")return!1;throw new WebhookCommandError("WEBHOOK_TOGGLE_INVALID",`${flag2} must be 'on' or 'off'.`)}__name(parseOnOff,"parseOnOff");function renderJson(command,data){ui.result({command,data,render:__name(()=>JSON.stringify(data,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","logs","validate","update","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["environments","status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","inbox","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option2=>formatItem(helper.styleOptionTerm(helper.optionTerm(option2)),helper.styleOptionDescription(helper.optionDescription(option2))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option2=>formatItem(helper.styleOptionTerm(helper.optionTerm(option2)),helper.styleOptionDescription(helper.optionDescription(option2))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
|
|
1006
1006
|
`)}__name(formatHelpWithGroupedCommands,"formatHelpWithGroupedCommands");function formatGroupedCommandSections(cmd,helper,groups,termWidth){let visibleCommands=helper.visibleCommands(cmd);if(visibleCommands.length===0)return[];let commandByName=new Map(visibleCommands.map(command=>[command.name(),command])),renderedNames=new Set,sections=[];for(let group of groups){let rows=group.commands.map(name=>commandByName.get(name)).filter(command=>command!==void 0).map(command=>(renderedNames.add(command.name()),indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper))));rows.length>0&&(sections.length>0&§ions.push(""),sections.push(` ${group.title}:`,...rows))}let ungroupedRows=visibleCommands.filter(command=>!renderedNames.has(command.name())).map(command=>indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper)));return ungroupedRows.length>0&&(sections.length>0&§ions.push(""),sections.push(" Other commands:",...ungroupedRows)),sections}__name(formatGroupedCommandSections,"formatGroupedCommandSections");function indentBlock(value){return value.split(`
|
|
1007
1007
|
`).map(line=>` ${line}`).join(`
|
|
1008
|
-
`)}__name(indentBlock,"indentBlock");init_sdk_transport();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs49.readFileSync(path51.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs49.readFileSync(path51.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--branch <name>","Override the
|
|
1008
|
+
`)}__name(indentBlock,"indentBlock");init_sdk_transport();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs49.readFileSync(path51.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs49.readFileSync(path51.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--branch <name>","Override the target Branch (analytics reads default to prod; other commands use the current Git branch or FIMO_ENV)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerMcpCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerInboxCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--branch <name>","Branch to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--branch <name>","Branch to link (defaults to the current git branch, else main)").option("--relink","Replace an existing link to a different project").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--branch <name>","Branch to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory when creating").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Set up a Fimo project as the target of an agent-driven migration").action(()=>{migrate.help()});migrate.command("init").description("Set up the migration target: link or create its Fimo project, scaffold it, and push the first commit").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--project-id <projectId>","Link an owner-supplied existing project (delegates to `fimo init`)").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--source-platform <platform>","Where the site comes from: webflow | framer | squarespace | wix | carrd | wordpress | nextjs | astro | react-router | other").option("--json","Output the setup receipt as JSON").action((dir,_options,command)=>migrateInitCommand(dir,command.optsWithGlobals()));program.command("deploy").description("Push the current Branch to Fimo and deploy to Preview (use --publish from the Production source)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--no-wait","Don't wait for the deployed preview to serve a page. Validation, push, and sandbox sync are still waited for; the result reports readiness as skipped. Not a substitute for --no-restart.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);addPaginationOptions(program.command("logs").description("Show the current Branch sandbox's dependency-install and dev-server output (newest first)"),{defaultLimit:200,maxLimit:1e3,legacyCursor:"before"}).option("-C, --cwd <dir>","Run against this directory instead of cwd").addHelpText("after",`
|
|
1009
1009
|
Logs come from the sandbox's own process buffers, so they end when the sandbox does.
|
|
1010
1010
|
There is no --follow; re-run the command instead.
|
|
1011
|
-
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("update").description("Update this checkout's Fimo packages to an exact release and apply the bundled migrations").argument("<version>","Exact target version, for example 1.0.0").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--dry-run","Show the update plan without writing anything").option("--apply","Apply without prompting (required in --json / non-interactive shells)").option("--allow-dirty","Skip the clean-working-tree check").option("--no-install","Skip dependency installation after applying").option("--no-validate","Skip `fimo validate` after applying").action(updateCommand3);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--branch <name>","Branch to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);projects.command("transfer").description("Move a project to another organization you administer (defaults to the current project)").argument("[projectId]","Explicit project ID").option("--to <organization>","Destination organization ID or slug").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsTransferCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (requires an eligible plan)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: remove dist/server and preserve dist/client assets (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete Branches (a Branch = git branch + its own Neon DB + sandbox)").argument("[name]","Branch name (omit to list)").option("-v, --verbose","Include deleted Branches").option("--all","Also list Fimo's own agent Branches (task/*), normally hidden").option("-d, --delete","Delete the named Branch (drops sandbox + Neon branch + R2 prefix)").option("--from <branch>","Parent Branch to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to a Branch (or create + switch with -b)").argument("<name>","Branch name").option("-b, --create","Create the Branch if it does not exist").option("--from <branch>","Parent Branch (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch Branches)").argument("<name>","Branch name").action(checkoutCommand);program.command("pull").description("Sync the current Branch's data plane from its parent").option("--from <branch>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-Branch diff across all surfaces").argument("[from]","From Branch (defaults to the current Branch)").argument("[to]","To Branch (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another Branch into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source Branch").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);var publish=program.command("publish").description("Publish main using a stable Fimo publication ID").option("-C, --cwd <dir>","Project directory").option("--label <text>","Optional human-readable publication label").option("--notes <text>","Optional publication notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);addPaginationOptions(publish.command("list").description("Publication attempts for the current project, newest first"),{defaultLimit:20,maxLimit:100,legacyCursor:"before"}).option("-C, --cwd <dir>","Project directory").action(publishListCommand);publish.command("inspect").description("One publication attempt in full, including why it failed").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").action(publishInspectCommand);publish.command("logs").description("Read a publication's build log from its hosting provider").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Events to return (1-1000, default 200)").action(publishLogsCommand);program.command("status").description("Multi-surface Branch status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <branch>","Comparison target (defaults to the parent Branch or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");addPaginationOptions(entries.command("list").description("List entries of a content type"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");addPaginationOptions(assets2.command("list").description("List assets"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").action(assetsListCommand);assets2.command("read").description("Read canonical asset text or ask one targeted question").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--cursor <next-cursor>","Continue an exact read from a previous nextCursor").option("--query <question>","Ask one targeted model-backed question").action(assetsReadCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);assets2.command("bulk-upload").description("Upload files from a structured JSON manifest").requiredOption("--file <path>","JSON manifest path").option("-C, --cwd <dir>","Project directory").option("--concurrency <n>","Maximum parallel uploads","4").action(assetsBulkUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("usage").description("Check Current, Main, and Live structured-reference impact").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsUsageCommand);assets2.command("replace").description("Replace structured references in the Current Branch").argument("<id>","Source asset ID").requiredOption("--with <id>","Replacement asset ID").option("-C, --cwd <dir>","Project directory").action(assetsReplaceCommand);assets2.command("remove").alias("delete").description("Safely remove an asset from the current Branch").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--replace-with <id>","Replace references before removal (Current Branch content and source; every Branch and Live with --permanent)").option("--without-checking","Skip reference guidance before environment removal").option("--permanent","Destroy the asset across the project").option("-y, --yes","Skip confirmation for permanent destruction").action(assetsRemoveCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1011
|
+
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("update").description("Update this checkout's Fimo packages to an exact release and apply the bundled migrations").argument("<version>","Exact target version, for example 1.0.0").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--dry-run","Show the update plan without writing anything").option("--apply","Apply without prompting (required in --json / non-interactive shells)").option("--allow-dirty","Skip the clean-working-tree check").option("--no-install","Skip dependency installation after applying").option("--no-validate","Skip `fimo validate` after applying").action(updateCommand3);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--branch <name>","Branch to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);projects.command("transfer").description("Move a project to another organization you administer (defaults to the current project)").argument("[projectId]","Explicit project ID").option("--to <organization>","Destination organization ID or slug").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsTransferCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (requires an eligible plan)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: remove dist/server and preserve dist/client assets (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete Branches (a Branch = git branch + its own Neon DB + sandbox)").argument("[name]","Branch name (omit to list)").option("-v, --verbose","Include deleted Branches").option("--all","Also list Fimo's own agent Branches (task/*), normally hidden").option("-d, --delete","Delete the named Branch (drops sandbox + Neon branch + R2 prefix)").option("--from <branch>","Parent Branch to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to a Branch (or create + switch with -b)").argument("<name>","Branch name").option("-b, --create","Create the Branch if it does not exist").option("--from <branch>","Parent Branch (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch Branches)").argument("<name>","Branch name").action(checkoutCommand);program.command("pull").description("Sync the current Branch's data plane from its parent").option("--from <branch>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-Branch diff across all surfaces").argument("[from]","From Branch (defaults to the current Branch)").argument("[to]","To Branch (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another Branch into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source Branch").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);var publish=program.command("publish").description("Publish main using a stable Fimo publication ID").option("-C, --cwd <dir>","Project directory").option("--label <text>","Optional human-readable publication label").option("--notes <text>","Optional publication notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);addPaginationOptions(publish.command("list").description("Publication attempts for the current project, newest first"),{defaultLimit:20,maxLimit:100,legacyCursor:"before"}).option("-C, --cwd <dir>","Project directory").action(publishListCommand);publish.command("inspect").description("One publication attempt in full, including why it failed").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").action(publishInspectCommand);publish.command("logs").description("Read a publication's build log from its hosting provider").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Events to return (1-1000, default 200)").action(publishLogsCommand);program.command("status").description("Multi-surface Branch status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <branch>","Comparison target (defaults to the parent Branch or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");addPaginationOptions(entries.command("list").description("List entries of a content type"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");addPaginationOptions(assets2.command("list").description("List assets"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").action(assetsListCommand);assets2.command("read").description("Read canonical asset text or ask one targeted question").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--cursor <next-cursor>","Continue an exact read from a previous nextCursor").option("--query <question>","Ask one targeted model-backed question").action(assetsReadCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);assets2.command("bulk-upload").description("Upload files from a structured JSON manifest").requiredOption("--file <path>","JSON manifest path").option("-C, --cwd <dir>","Project directory").option("--concurrency <n>","Maximum parallel uploads","4").action(assetsBulkUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("usage").description("Check Current, Main, and Live structured-reference impact").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsUsageCommand);assets2.command("replace").description("Replace structured references in the Current Branch").argument("<id>","Source asset ID").requiredOption("--with <id>","Replacement asset ID").option("-C, --cwd <dir>","Project directory").action(assetsReplaceCommand);assets2.command("remove").alias("delete").description("Safely remove an asset from the current Branch").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--replace-with <id>","Replace references before removal (Current Branch content and source; every Branch and Live with --permanent)").option("--without-checking","Skip reference guidance before environment removal").option("--permanent","Destroy the asset across the project").option("-y, --yes","Skip confirmation for permanent destruction").action(assetsRemoveCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1012
1012
|
Supported agents:
|
|
1013
1013
|
Universal (always covered via AGENTS.md, no per-agent file needed):
|
|
1014
1014
|
Codex, OpenCode, Aider, and other AGENTS.md-native tools
|
|
@@ -1018,7 +1018,7 @@ Supported agents:
|
|
|
1018
1018
|
|
|
1019
1019
|
All supported (use --agents=<id> for any of these):
|
|
1020
1020
|
${getSupportedAgentIds().sort().join(", ")}
|
|
1021
|
-
`,skills=program.command("skills").description("Manage Fimo skills for AI coding agents (global + project)");skills.command("install").description("Install the global Fimo skill for selected agents (loads the rest on demand via `skills get`)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("-y, --yes","Reserved (install is prompt-light)").addHelpText("after",supportedAgentsHelp).action(skillsInstallCommand);skills.command("sync").description("Re-ensure the global Fimo skill and clean up stale skills from older versions").option("--agents <list>","Limit the global refresh to this agent list (default: agents that already have the skills)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(skillsSyncCommand);skills.command("uninstall").description("Remove the global Fimo skills from selected AI agents (project files left untouched)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(skillsUninstallCommand);skills.command("list").description("List the Fimo skills bundled with this CLI (name, scope, reference count)").action(skillsListCommand);skills.command("get <name>").description("Print a bundled skill's SKILL.md (or a reference doc with --ref)").option("--ref <doc>","Print a reference doc instead (e.g. deploy, integrations/firecrawl)").action(skillsGetCommand);var rules=program.command("rules").description("Manage per-agent rule files for this project (CLAUDE.md, .cursor/rules/, etc.)");rules.command("sync").description("Regenerate per-agent rule files from this project's AGENTS.md (rule files only \u2014 skills live under `fimo skills`)").option("-C, --cwd <dir>","Project directory (defaults to cwd)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(rulesSyncCommand);var pages=program.command("pages").description("Manage the site's page registry");pages.command("list").description("List page templates and their binding status").option("-C, --cwd <dir>","Project directory").option("--expand","Materialize dynamic page instances from their bound schemas").action(pagesListCommand);pages.command("set <id>").description("Create or update a page template").option("-C, --cwd <dir>","Project directory").option("--path <path>","Route path in :param syntax, for example /blog/:slug").option("--label <label>","Display label shown in Studio").option("--group <group>","Editorial group shown in the Pages tree; pass an empty value to clear").option("--sources <json>","Named Labels, Single, and Collection sources as a JSON object").option("--clear-sources","Remove every declared source from the page").option("--icon <name>","Kebab-case Lucide icon name; pass an empty value to clear").option("--params <json>",
|
|
1021
|
+
`,skills=program.command("skills").description("Manage Fimo skills for AI coding agents (global + project)");skills.command("install").description("Install the global Fimo skill for selected agents (loads the rest on demand via `skills get`)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("-y, --yes","Reserved (install is prompt-light)").addHelpText("after",supportedAgentsHelp).action(skillsInstallCommand);skills.command("sync").description("Re-ensure the global Fimo skill and clean up stale skills from older versions").option("--agents <list>","Limit the global refresh to this agent list (default: agents that already have the skills)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(skillsSyncCommand);skills.command("uninstall").description("Remove the global Fimo skills from selected AI agents (project files left untouched)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(skillsUninstallCommand);skills.command("list").description("List the Fimo skills bundled with this CLI (name, scope, reference count)").action(skillsListCommand);skills.command("get <name>").description("Print a bundled skill's SKILL.md (or a reference doc with --ref)").option("--ref <doc>","Print a reference doc instead (e.g. deploy, integrations/firecrawl)").action(skillsGetCommand);var rules=program.command("rules").description("Manage per-agent rule files for this project (CLAUDE.md, .cursor/rules/, etc.)");rules.command("sync").description("Regenerate per-agent rule files from this project's AGENTS.md (rule files only \u2014 skills live under `fimo skills`)").option("-C, --cwd <dir>","Project directory (defaults to cwd)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(rulesSyncCommand);var pages=program.command("pages").description("Manage the site's page registry");pages.command("list").description("List page templates and their binding status").option("-C, --cwd <dir>","Project directory").option("--expand","Materialize dynamic page instances from their bound schemas").action(pagesListCommand);pages.command("set <id>").description("Create or update a page template").option("-C, --cwd <dir>","Project directory").option("--path <path>","Route path in :param syntax, for example /blog/:slug").option("--label <label>","Display label shown in Studio").option("--group <group>","Editorial group shown in the Pages tree; pass an empty value to clear").option("--sources <json>","Named Labels, Single, and Collection sources as a JSON object").option("--clear-sources","Remove every declared source from the page").option("--icon <name>","Kebab-case Lucide icon name; pass an empty value to clear").option("--params <json>",'Bindings from route params to content schemas, or {"<param>":{"type":"external"}} for values the application owns').option("--clear-params","Remove every content param binding from the page").action(pagesSetCommand);pages.command("rename <id> <new-id>").description("Rename a page registry id").option("-C, --cwd <dir>","Project directory").action(pagesRenameCommand);pages.command("delete <id>").description("Delete a page from the registry").option("-C, --cwd <dir>","Project directory").action(pagesDeleteCommand);var labels=program.command("labels").description("Manage site labels stored in Fimo");labels.command("list").description("List labels stored in the DB").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Filter by locale (e.g. en)").action(labelsListCommand);labels.command("set <key> [value]").description("Set one label value").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Target locale (default en)").option("--value <value>","Label value").option("--stdin","Read the label value from stdin").action(labelsSetCommand);labels.command("set-many").description("Set many label values from JSON").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Target locale (default en)").option("--file <path>","JSON object map or array of { key, value, locale? } records").option("--data <json>","Inline JSON object map or array of { key, value, locale? } records").action(labelsSetManyCommand);labels.command("delete <key>").alias("unset").description("Delete one label value").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Target locale (default en)").action(labelsDeleteCommand);var analytics=program.command("analytics").description("Read published-site analytics (defaults to prod; --branch overrides reads; annotation writes use the current Branch)"),rangeOptions=__name(cmd=>(cmd.option("-C, --cwd <dir>","Project directory").option("--preset <preset>","Time range preset (today, yesterday, this_week, this_month, last_7_days, last_30_days, last_90_days, last_week, last_month, last_quarter, last_year, custom)").option("--group-by <unit>","Group by day | week | month | quarter").option("--from <date>","ISO date (YYYY-MM-DD) \u2014 required with --preset custom").option("--to <date>","ISO date (YYYY-MM-DD) \u2014 required with --preset custom").option("--days <n>","Shortcut for last N days (7, 30, or 90)").option("--device <device>","Narrow to one device: bot | desktop | mobile | tablet"),cmd),"rangeOptions");rangeOptions(analytics.command("pageviews").description("Show headline analytics: visitors, pageviews, bounce rate, top breakdowns")).action(analyticsPageviewsCommand);rangeOptions(analytics.command("top").description("Show a single dimension breakdown (pages | browsers | devices | countries | sources)").argument("<dimension>","Which dimension to show").option("--limit <n>","Truncate to the first N results")).action(analyticsTopCommand);var annotations=analytics.command("annotations").description("Manage analytics annotations (per-day notes)");rangeOptions(annotations.command("list").description("List annotations in the project's date range")).action(analyticsAnnotationsListCommand);annotations.command("set").description("Upsert an annotation. Empty content deletes (matches the API).").argument("<date>","YYYY-MM-DD").argument("<content>",'Annotation text (use "" to delete)').option("-C, --cwd <dir>","Project directory").action(analyticsAnnotationsSetCommand);annotations.command("delete").description("Delete an annotation on a given date").argument("<date>","YYYY-MM-DD").option("-C, --cwd <dir>","Project directory").action(analyticsAnnotationsDeleteCommand);var formsSubmissions=forms2.command("submissions").description("Manage submissions intake for a form (list, get, stats, delete)");addPaginationOptions(formsSubmissions.command("list").description("List submissions for a form (newest first by default)"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<formIdOrName>","Form ID (UUID) or its name").option("-C, --cwd <dir>","Project directory").option("--search <query>","Search query passed to the API").option("--sort <direction>","Sort direction ('asc' or 'desc')").action(formsSubmissionsListCommand);formsSubmissions.command("get").description("Get a single submission").argument("<formIdOrName>","Form ID (UUID) or its name").argument("<submissionId>","Submission ID").option("-C, --cwd <dir>","Project directory").action(formsSubmissionsGetCommand);formsSubmissions.command("stats").description("Aggregate submission counts for a form").argument("<formIdOrName>","Form ID (UUID) or its name").option("-C, --cwd <dir>","Project directory").action(formsSubmissionsStatsCommand);formsSubmissions.command("delete").description("Permanently delete a single submission (cannot be undone)").argument("<formIdOrName>","Form ID (UUID) or its name").argument("<submissionId>","Submission ID").option("-C, --cwd <dir>","Project directory").action(formsSubmissionsDeleteCommand);configureGroupedHelp(program);program.addHelpText("after",`
|
|
1022
1022
|
Examples:
|
|
1023
1023
|
fimo init my-site Set up a new project
|
|
1024
1024
|
fimo deploy Push to preview
|
|
@@ -1031,7 +1031,7 @@ Run \`fimo <command> --help\` for command-specific help.
|
|
|
1031
1031
|
`);process.argv.slice(2).length===0&&process.stdout.write(`
|
|
1032
1032
|
Get started:
|
|
1033
1033
|
fimo init Sign in, create or link a project, install deps + skills
|
|
1034
|
-
`);var execution;hasRemovedPublishVersion(process.argv)?(initUi({json:process.argv.includes("--json"),noColor:process.argv.includes("--no-color"),ascii:process.argv.includes("--ascii"),jsonEnvVar:"FIMO_OUTPUT"}),rejectRemovedPublishVersion(),execution=Promise.resolve()):execution=program.parseAsync(process.argv);execution.catch(err=>{let command=process.argv[2]??"fimo";if(isCliAuthError(err)){if(currentMode().format==="json")if(err instanceof PermissionDeniedError)ui.error({command,code:"PERMISSION_DENIED",message:err.message,hint:err.required.length?`Your role lacks \`${err.required.join(", ")}\` on this project \u2014 ask a project admin for access.`:"Your role does not allow this action on this project \u2014 ask a project admin for access."});else{let isExpired=err instanceof UnauthorizedError;ui.error({command,code:isExpired?"SESSION_EXPIRED":"NOT_AUTHENTICATED",message:err.message,hint:isExpired?"Run `fimo login` to refresh.":"Run `fimo login` to sign in."})}else renderCliAuthError(err);process.exit(1)}err instanceof NotInProjectError&&(ui.error({command,code:"NOT_IN_PROJECT",message:err.message,hint:"Run `fimo init <dir>` or `cd` into a linked Fimo project."}),process.exit(1)),err instanceof GitBranchUndetectedError&&(ui.error({command,code:"GIT_BRANCH_UNDETECTED",message:err.message,hint:"Pass `--branch <name>` explicitly, or check out a branch (e.g. `git checkout main`)."}),process.exit(1)),err instanceof InvalidBranchOverrideError&&(ui.error({command,code:"INVALID_ENV_OVERRIDE",message:err.message,hint:"Branch names must match /^[a-zA-Z0-9._/-]+$/ \u2014 e.g. `main`, `feat/seo`, `release/v1`."}),process.exit(1)),err instanceof BranchNotFoundError&&(ui.error({command,code:"ENV_NOT_FOUND",message:err.message,hint:"Run `fimo branch` to list Branches, or `fimo branch <name>` to create the one you want."}),process.exit(1)),err instanceof SchemaCommandError&&(ui.error({command,code:err.code,message:err.message}),process.exit(1)),err instanceof EntriesInputError&&(ui.error({command,code:"INVALID_ENTRY_INPUT",message:err.message}),process.exit(1)),err instanceof SinglesInputError&&(ui.error({command,code:"INVALID_SINGLE_INPUT",message:err.message}),process.exit(1)),err instanceof WebhookCommandError&&(ui.error({command,code:err.code,message:err.message}),process.exit(1)),ui.error({command,code:"COMMAND_FAILED",message:formatZodIssues(err)??(err instanceof Error?err.message:String(err))}),process.exit(1)});
|
|
1034
|
+
`);var execution;hasRemovedPublishVersion(process.argv)?(initUi({json:process.argv.includes("--json"),noColor:process.argv.includes("--no-color"),ascii:process.argv.includes("--ascii"),jsonEnvVar:"FIMO_OUTPUT"}),rejectRemovedPublishVersion(),execution=Promise.resolve()):execution=program.parseAsync(process.argv);execution.catch(err=>{let command=process.argv[2]??"fimo";if(isCliAuthError(err)){if(currentMode().format==="json")if(err instanceof PermissionDeniedError)ui.error({command,code:"PERMISSION_DENIED",message:err.message,hint:err.required.length?`Your role lacks \`${err.required.join(", ")}\` on this project \u2014 ask a project admin for access.`:"Your role does not allow this action on this project \u2014 ask a project admin for access."});else{let isExpired=err instanceof UnauthorizedError;ui.error({command,code:isExpired?"SESSION_EXPIRED":"NOT_AUTHENTICATED",message:err.message,hint:isExpired?"Run `fimo login` to refresh.":"Run `fimo login` to sign in."})}else renderCliAuthError(err);process.exit(1)}err instanceof NotInProjectError&&(ui.error({command,code:"NOT_IN_PROJECT",message:err.message,hint:"Run `fimo init <dir>` or `cd` into a linked Fimo project."}),process.exit(1)),err instanceof GitBranchUndetectedError&&(ui.error({command,code:"GIT_BRANCH_UNDETECTED",message:err.message,hint:"Pass `--branch <name>` explicitly, or check out a branch (e.g. `git checkout main`)."}),process.exit(1)),err instanceof InvalidBranchOverrideError&&(ui.error({command,code:"INVALID_ENV_OVERRIDE",message:err.message,hint:"Branch names must match /^[a-zA-Z0-9._/-]+$/ \u2014 e.g. `main`, `feat/seo`, `release/v1`."}),process.exit(1)),err instanceof BranchNotFoundError&&(ui.error({command,code:"ENV_NOT_FOUND",message:err.message,hint:"Run `fimo branch` to list Branches, or `fimo branch <name>` to create the one you want."}),process.exit(1)),err instanceof SchemaCommandError&&(ui.error({command,code:err.code,message:err.message}),process.exit(1)),err instanceof EntriesInputError&&(ui.error({command,code:"INVALID_ENTRY_INPUT",message:err.message}),process.exit(1)),reportSingleContentTypeError(command,err)&&process.exit(1),err instanceof SinglesInputError&&(ui.error({command,code:"INVALID_SINGLE_INPUT",message:err.message}),process.exit(1)),err instanceof WebhookCommandError&&(ui.error({command,code:err.code,message:err.message}),process.exit(1)),ui.error({command,code:"COMMAND_FAILED",message:formatZodIssues(err)??(err instanceof Error?err.message:String(err))}),process.exit(1)});
|
|
1035
1035
|
/*! Bundled license information:
|
|
1036
1036
|
|
|
1037
1037
|
smol-toml/dist/error.js:
|