fimo 0.16.0-staging.4 → 0.16.0-staging.5
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 +4 -4
- package/assets/skills/fimo-cli/references/branches.md +2 -2
- package/assets/skills/fimo-cli/references/deploy.md +12 -9
- package/assets/skills/fimo-cli/references/init.md +2 -2
- package/assets/skills/fimo-cli/references/integrations/firecrawl.md +2 -0
- package/assets/skills/fimo-cli/references/preview.md +26 -20
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +9 -7
- package/dist/runtime/app/FimoProviders.js +1 -1
- package/dist/runtime/app/prefetch.js +1 -1
- package/dist/runtime/i18n/locale.d.ts +2 -3
- package/dist/runtime/i18n/locale.js +2 -27
- package/dist/runtime/paths/get-fimo-paths.js +1 -1
- package/dist/runtime/react-router/legacy/routes.js +1 -1
- package/dist/runtime/routes/index.d.ts +161 -2
- package/dist/runtime/routes/index.js +335 -3
- package/dist/runtime/seo/resolver.js +1 -1
- package/dist/runtime/shared/fimo-config.types.d.ts +4 -29
- package/dist/scripts/validate-route-metadata.js +1 -1
- package/package.json +4 -3
- package/templates/react-router/package.json +1 -1
- package/dist/runtime/routes/contract.d.ts +0 -116
- package/dist/runtime/routes/contract.js +0 -377
package/dist/cli/index.js
CHANGED
|
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
|
|
|
39
39
|
`),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process9.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process9.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
|
|
40
40
|
`),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path49.basename(filename,path49.extname(filename)),this}executableDir(path50){return path50===void 0?this._executableDir:(this._executableDir=path50,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process9.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
|
|
41
41
|
Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
|
|
42
|
-
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue2=data2[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});import{z as z6}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z6.union([z6.literal(PRODUCTION_ENVIRONMENT_KEY),z6.literal(PREVIEW_ENVIRONMENT_KEY),z6.uuid()]),CustomEnvironmentSchema=z6.object({id:z6.uuid(),projectId:z6.uuid(),name:z6.string().trim().min(1).max(64),branchPatterns:z6.array(z6.string().min(1).max(255)).min(1),description:z6.string().max(255).nullable()}),ResolvedEnvironmentSchema=z6.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});import{z as z7}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z7.preprocess(referenceValuePreprocess,z7.object({documentId:z7.uuid()})),ReferenceInputValueSchema=z7.preprocess(referenceValuePreprocess,z7.union([z7.object({documentId:z7.uuid()}),z7.object({slug:z7.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.object({contentType:z7.string().min(1),documentId:z7.uuid()})),PolymorphicReferenceInputValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.union([z7.object({contentType:z7.string().min(1),documentId:z7.uuid()}),z7.object({contentType:z7.string().min(1),slug:z7.string().min(1)})]))}});import{z as z8}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path49){let conditionPath=[...path49,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,path49)=>{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,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z8.union([z8.object({field:z8.string().min(1),equals:z8.union([z8.string(),z8.number(),z8.boolean()])}).strict(),z8.object({field:z8.string().min(1),in:z8.array(z8.union([z8.string(),z8.number(),z8.boolean()])).min(1)}).strict()]),commonFieldShape={label:z8.string().min(1).optional(),description:z8.string().optional(),editable:z8.boolean().optional(),required:z8.boolean().optional(),default:z8.unknown().optional(),showIf:z8.union([showIfClauseSchema,z8.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z8.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z8.object({...commonFieldShape,type:z8.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z8.number().optional(),max:z8.number().optional(),minLength:z8.number().int().nonnegative().optional(),maxLength:z8.number().int().nonnegative().optional(),regex:z8.string().optional(),multiple:z8.boolean().optional(),allowedMimeTypes:z8.array(z8.string()).optional(),options:z8.array(z8.string().min(1)).min(1).optional(),unique:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z8.object({...commonFieldShape,type:z8.literal("reference"),target:z8.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z8.array(z8.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z8.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z8.record(z8.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z8.object({uid:z8.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z8.string().min(1),description:z8.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z8.object({fields:blockFieldsSchema}).strict(),blocksSchema=z8.object({oneOf:z8.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z8.object({...commonFieldShape,type:z8.literal("blocks"),min:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z8.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z8.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z9}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z9.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z9.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z9.enum(AUDIT_ACTOR_KINDS)}});import{z as z10}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z10.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z10.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z10.object({permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),enabled:z10.boolean().default(!0)}),OpsServiceTokenInputSchema=z10.object({name:z10.string().trim().min(1).max(120),permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),expiresAt:z10.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z10.object({importanceReason:z10.string().trim().min(1).max(1e3),ownerUserId:z10.string().trim().min(1).nullable().optional(),framework:z10.string().trim().max(120).nullable().optional(),packageManager:z10.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z10.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z10.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z10.object({projectId:z10.uuid(),title:z10.string().trim().min(1).max(240),userReport:z10.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z10.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z10.string().trim().max(1e4).nullable().optional(),outcome:z10.string().trim().max(1e4).nullable().optional(),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z10.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z10.object({fingerprint:z10.string().trim().min(1).max(240),title:z10.string().trim().min(1).max(240),description:z10.string().trim().min(1).max(1e4),affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z10.string().trim().min(1).max(64).nullable().optional(),workaround:z10.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z10.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z10.object({changeReference:z10.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z10.string().trim().min(1).max(1e4),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z10.object({recipientEmail:z10.email().optional(),subject:z10.string().trim().min(1).max(200).default("An update from Fimo"),message:z10.string().trim().min(1).max(5e3),locale:z10.string().trim().min(2).max(20),reason:z10.string().trim().min(1).max(1e3),acknowledgePolicy:z10.literal(!0)}),OpsSentryIssueIdSchema=z10.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z10.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z10.object({projectId:z10.uuid(),from:z10.coerce.date(),to:z10.coerce.date(),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBillingCacheInvalidateInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z10.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z10.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z10.object({kind:z10.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z10.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z10.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z10.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z10.object({migrationId:OpsMigrationIdSchema,projectEnv:z10.string().trim().min(1).max(255).default("main"),reason:z10.string().trim().min(1).max(1e3)}),OpsProjectOperationApplyInputSchema=z10.intersection(OpsProjectOperationPlanInputSchema,z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z11}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z11.object({kind:z11.literal("say"),label:z11.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z11.string().min(1).max(240).optional(),message:z11.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z11.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z11.object({kind:z11.literal("app"),command:z11.literal("publish")}).strict(),BlockBaseSchema=z11.object({fallback:z11.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z11.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z11.literal("choices"),text:z11.string().max(500).optional(),actions:z11.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z11.discriminatedUnion("kind",[z11.object({kind:z11.literal("entry"),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("asset"),assetId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("url"),url:z11.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z11.literal("table"),columns:z11.array(z11.object({label:z11.string().min(1).max(24)})).min(2).max(4),rows:z11.array(z11.object({cells:z11.array(z11.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z11.literal("cards"),layout:z11.enum(["rail","stack"]).optional(),items:z11.array(z11.object({title:z11.string().min(1).max(60),subtitle:z11.string().min(1).max(120).optional(),imageUrl:z11.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z11.literal("entry"),label:z11.string().min(1).max(80),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120),path:z11.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z11.literal("assets"),items:z11.array(z11.object({url:z11.url({protocol:/^https$/}).max(2e3),alt:z11.string().min(1).max(120),label:z11.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z11.literal("callout"),title:z11.string().min(1).max(80),text:z11.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z11.literal("stat"),items:z11.array(z11.object({label:z11.string().min(1).max(24),value:z11.string().min(1).max(16),delta:z11.string().min(1).max(12).optional(),tone:z11.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z11.literal("chart"),unit:z11.string().min(1).max(12).optional(),points:z11.array(z11.object({label:z11.string().min(1).max(12),value:z11.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z11.object({question:z11.string().min(1).max(500),header:z11.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z11.boolean(),recommended:z11.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z11.literal("form"),steps:z11.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z11.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z11.object({header:z11.string().min(1).max(25),question:z11.string().min(1).max(500),answer:z11.string().min(1).max(3e3),selectedLabels:z11.array(z11.string().min(1).max(120)).max(8),freeText:z11.string().max(2e3),skipped:z11.boolean()}),ChatFormAnswerMetadataSchema=z11.object({toolCallId:z11.string().max(255).optional(),shortTitle:z11.string().max(80).optional(),questions:z11.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z11.string().min(1).max(255)})}});import{z as z12}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingRewriteSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z12.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z12.object({dev:z12.string().trim().min(1).optional(),build:z12.string().trim().min(1).optional(),install:z12.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z12.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z12.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingRewriteSchema=z12.object({source:z12.string().min(1),destination:z12.string().min(1)}),FimoHostingConfigSchema=z12.object({rewrites:z12.array(FimoHostingRewriteSchema).optional()}).strict(),FimoAppConfigSchema=z12.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path49){return[...path49.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path49){return pageRouteParamNames(path49).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record2=value;return typeof record2.id=="string"?record2.id:Object.fromEntries(Object.entries(record2).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z13}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z13.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z13.string(),displayName:z13.string().nullable(),subdomain:z13.string().nullable().optional(),subdomainUpdatedAt:z13.date().nullable().optional(),organizationId:z13.string().nullable(),createdBy:z13.string().nullable(),previewEnabled:z13.boolean().default(!0),enabledChatModels:z13.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z13.string(),thumbnailUrl:z13.string().nullable(),publishedThumbnailUrl:z13.string().nullable(),category:z13.string().nullable(),appUrl:z13.string().nullable(),lastPublishedAt:z13.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z13.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z13.object({id:z13.uuid(),name:z13.string(),displayName:z13.string().nullable(),thumbnailUrl:z13.string().nullable(),category:z13.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z13.object({id:z13.string(),name:z13.string(),avatar:z13.string().nullable(),color:z13.object({bg:z13.string(),text:z13.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z13.object({path:z13.string(),content:z13.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z13.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z13.object({id:z13.string(),messageId:z13.string(),versionId:z13.string().nullable(),role:ProjectChatMessageRole,parts:z13.array(z13.any()),createdAt:z13.coerce.date()}),MessageUserMetadataSchema=z13.object({id:z13.string(),name:z13.string().nullable().optional(),image:z13.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z13.number(),metadata:z13.object({user:MessageUserMetadataSchema,changeManifest:z13.array(z13.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z13.object({versionId:z13.uuid(),commitHash:z13.string(),name:z13.string(),description:z13.string().nullable(),kind:z13.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z13.object({versionCount:z13.number().int().nonnegative(),snapshotBytes:z13.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z13.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z13.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z13.object({content:z13.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z13.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z13.object({success:z13.boolean(),message:z13.string().optional(),warning:z13.string().optional(),durationMs:z13.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z13.object({isPublished:z13.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z13.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z13.object({success:z13.boolean(),message:z13.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z13.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z14}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,ResolvedBranchEnvironmentDTOSchema,ProjectEnvListItemDTOSchema,ProjectEnvListItemDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectEnvStatusSchema=z14.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z14.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z14.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,previewUrl:z14.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z14.string().nullable(),deletedAt:z14.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z14.object({id:z14.union([z14.literal(PREVIEW_ENVIRONMENT_KEY),z14.uuid()]),name:z14.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z14.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z14.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z14.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z14.object({surface:z14.enum(["code","schemas","content","translations","assets","forms"]),status:z14.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z14.number().int().nonnegative(),conflictCount:z14.number().int().nonnegative()}),EnvDiffResultSchema=z14.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z14.coerce.date(),surfaces:z14.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z15}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z15.object({projectId:z15.uuid(),name:z15.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z15.literal("production"),sourceBranch:EnvSchema,isPublished:z15.boolean(),url:z15.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PREVIEW_ENVIRONMENT_KEY),kind:z15.literal("preview"),matchedBranchCount:z15.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z15.literal("custom"),matchedBranchCount:z15.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z15.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z15.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z15.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z15.object({deletedId:z15.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z16}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z16.object({kind:z16.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z16.object({kind:z16.enum(["variable","secret"]),value:z16.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z16.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z16.object({kind:z16.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z16.object({id:z16.uuid(),projectId:z16.uuid(),key:z16.string(),kind:z16.literal("secret"),exposure:z16.literal("private"),environment:EnvironmentKeySchema,maskedValue:z16.string().optional(),createdAt:z16.date().transform(value=>value.toISOString()),updatedAt:z16.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z16.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z17}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z17.object({success:z17.literal(!0),downloadUrl:z17.string(),expiresAt:z17.string(),fileSize:z17.number(),duration:z17.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z17.object({success:z17.literal(!0),projectId:z17.string(),projectName:z17.string(),displayName:z17.string(),projectUrl:z17.string(),duration:z17.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z17.object({contentTypes:z17.number(),entries:z17.number(),assets:z17.number(),translations:z17.number(),forms:z17.number(),codeFiles:z17.number(),assetFiles:z17.number()}),ImportPreviewSurfaceDTOSchema=z17.object({name:z17.string(),included:z17.boolean(),count:z17.number().optional(),note:z17.string().optional()}),ImportPreviewDTOSchema=z17.object({projectName:z17.string(),displayName:z17.string().nullable(),category:z17.string().nullable(),exportedAt:z17.string(),version:z17.string(),envScope:z17.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z17.array(ImportPreviewSurfaceDTOSchema),fileSize:z17.number(),fileName:z17.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z17.object({success:z17.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z18}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z18.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z18.object({type:z18.literal("manual")}),ScheduleTriggerSchema=z18.object({type:z18.literal("schedule"),cron:z18.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z18.string().optional()}),WebhookTriggerSchema=z18.object({type:z18.literal("webhook"),path:z18.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z18.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemTriggerStateSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z20.boolean(),wired:z20.boolean(),syncError:z20.string().nullable()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),triggerStates:z20.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z21.object({args:z21.unknown().optional(),requestId:z21.string().min(1).max(128).optional()}),DispatchSkippedSchema=z21.object({skipped:z21.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z21.object({sessionId:z21.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z21.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z23.object({cpuMs:z23.number().nonnegative().default(0),netBytes:z23.number().nonnegative().default(0),walltimeMs:z23.number().nonnegative().default(0),llmTokensIn:z23.number().nonnegative().optional(),llmTokensOut:z23.number().nonnegative().optional(),stepCount:z23.number().int().nonnegative().optional(),toolCallCounts:z23.record(z23.string().min(1).max(120),z23.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),env:EnvSchema,agentName:z23.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z23.unknown().optional(),capabilities:z23.array(z23.string()).optional(),dataSources:z23.array(z23.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z23.string().nullable(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),cancelledAt:z23.coerce.date().nullable(),costUsd:z23.number().nonnegative(),costCeilingUsd:z23.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z23.boolean(),lastCheckpointId:z23.uuid().nullable(),branchEnvId:z23.uuid().nullable(),parentSessionId:z23.uuid().nullable(),terminalReason:z23.string().nullable(),errorMessage:z23.string().nullable(),report:z23.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z23.object({id:z23.uuid(),sessionId:z23.uuid(),checkpointIdx:z23.number().int().nonnegative(),payloadRef:z23.string(),payloadSizeBytes:z23.number().int().nonnegative(),checksum:z23.string().length(64),createdAt:z23.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z23.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z23.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z23.object({session:AgentSessionDTOSchema,checkpoints:z23.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z23.object({reason:z23.string().min(1).max(120).optional()})}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z25.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z25.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z25.enum(["secret_text"]),IntegrationCredentialUsageSchema=z25.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z25.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z25.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z25.object({mode:IntegrationAuthModeSchema,label:z25.string().min(1),description:z25.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z25.object({id:z25.string().min(1),label:z25.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z25.boolean()}),IntegrationToolDefinitionDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),description:z25.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z25.object({title:z25.string().min(1),description:z25.string().min(1),command:z25.string().min(1).optional()}),IntegrationInfoDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z25.array(IntegrationAuthModeDTOSchema),credentials:z25.array(IntegrationCredentialDefinitionDTOSchema),tools:z25.array(IntegrationToolDefinitionDTOSchema),recipes:z25.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),installed:z25.boolean(),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z25.string().nullable(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),connectionStatus:z25.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),installedAt:z25.coerce.date().nullable(),updatedAt:z25.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z25.string(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z25.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z25.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z25.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z25.object({value:z25.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z25.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z25.object({id:z25.uuid(),organizationId:z25.string().min(1),integrationKey:z25.string().min(1),alias:z25.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z25.string().min(1),externalAccountName:z25.string().nullable(),externalBotUserId:z25.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z25.array(z25.string()),connectedAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z25.object({alias:z25.string().min(1).max(120).optional(),token:z25.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z25.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),alias:z25.string().min(1).max(120),token:z25.string().min(1)}),z25.object({mode:z25.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z25.object({integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),integrationKey:z25.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z25.object({mode:z25.literal("oauth"),integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()})]),BindProjectChannelRequestSchema=z25.object({ref:z25.string().min(1),connectionAlias:z25.string().min(1).optional(),agentName:z25.string().min(1).max(160).nullable().optional(),force:z25.boolean().optional()}),ListProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1)}),SearchProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1),connectionAlias:z25.string().min(1),query:z25.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),connectionId:z25.uuid(),externalWorkspaceId:z25.string().min(1),externalChannelId:z25.string().min(1),externalChannelName:z25.string().nullable(),agentName:z25.string().nullable(),enabled:z25.boolean(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z25.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z25.object({id:z25.string().min(1),name:z25.string().min(1),visibility:z25.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z25.string().min(1).nullable(),canMove:z25.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z25.object({markdown:z25.boolean().optional(),summary:z25.boolean().optional(),links:z25.boolean().optional(),images:z25.boolean().optional(),html:z25.union([z25.literal("cleaned"),z25.literal("raw"),z25.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z25.object({url:z25.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z25.object({query:z25.string().min(1),maxResults:z25.number().int().positive().max(20).optional(),sources:z25.array(z25.enum(["web","news","images"])).min(1).max(3).optional(),categories:z25.array(z25.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z25.enum(["hour","day","week","month","year"]).optional(),location:z25.string().min(1).max(160).optional(),country:z25.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z25.object({url:z25.string().url(),search:z25.string().min(1).optional(),limit:z25.number().int().positive().max(200).optional(),includeSubdomains:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z25.object({url:z25.string().url(),limit:z25.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z25.object({text:z25.string().min(1).max(200).optional(),cron:z25.string().min(1).max(120).optional(),timezone:z25.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z25.object({type:z25.enum(["scrape","crawl"]).default("scrape"),urls:z25.array(z25.string().url()).min(1).max(50),scrapeOptions:z25.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z25.object({name:z25.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z25.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z25.string().min(1).max(2e3).optional(),judgeEnabled:z25.boolean().optional(),retentionDays:z25.number().int().min(1).max(365).optional(),notification:z25.object({email:z25.object({enabled:z25.boolean().default(!0),recipients:z25.array(z25.string().email()).min(1).max(20),includeDiffs:z25.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z25.object({monitorId:z25.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z25.string().uuid()}),RunProjectIntegrationToolRequestSchema=z25.object({tool:z25.string().min(1),input:z25.record(z25.string(),z25.unknown()),connectionAlias:z25.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z25.object({provider:z25.string().min(1),providerCredits:z25.number().nonnegative().optional(),providerCostUsd:z25.number().nonnegative().optional(),requests:z25.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z25.object({credits:z25.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()}),FirecrawlSearchToolOutputSchema=z25.object({query:z25.string(),provider:z25.literal("firecrawl"),warning:z25.string().optional(),results:z25.array(z25.object({title:z25.string(),url:z25.string(),snippet:z25.string().optional(),content:z25.string().optional(),score:z25.number().optional(),publishedAt:z25.string().optional()}))}),FirecrawlMapToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),count:z25.number(),links:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),description:z25.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),total:z25.number(),pages:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()})),warning:z25.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z25.object({cron:z25.string().optional(),text:z25.string().optional(),timezone:z25.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z25.object({id:z25.string().optional(),urls:z25.array(z25.string()).optional(),scrapeOptions:z25.record(z25.string(),z25.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z25.object({id:z25.string(),name:z25.string(),status:z25.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z25.string().nullable().optional(),lastRunAt:z25.string().nullable().optional(),currentCheckId:z25.string().nullable().optional(),targets:z25.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z25.string().nullable().optional(),judgeEnabled:z25.boolean().optional(),estimatedCreditsPerMonth:z25.number().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z25.object({id:z25.string(),monitorId:z25.string(),scheduledFor:z25.string().nullable().optional(),startedAt:z25.string().nullable().optional(),finishedAt:z25.string().nullable().optional(),estimatedCredits:z25.number().optional(),reservedCredits:z25.number().optional(),actualCredits:z25.number().optional(),billingStatus:z25.string().nullable().optional(),summary:z25.object({totalPages:z25.number().optional(),same:z25.number().optional(),changed:z25.number().optional(),new:z25.number().optional(),removed:z25.number().optional(),error:z25.number().optional()}).passthrough().optional(),error:z25.string().nullable().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitors:z25.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),deleted:z25.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),checks:z25.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),check:FirecrawlMonitorCheckOutputSchema,next:z25.string().optional()}),FirecrawlToolKeySchema=z25.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z25.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),tool:z25.string().min(1),connectionAlias:z25.string().min(1).nullable().optional(),output:z25.record(z25.string(),z25.unknown()),executedAt:z25.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z25.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z25.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z25.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z25.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z25.array(ProjectChannelCandidateDTOSchema))}});import{z as z26}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z26.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z26.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z26.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z26.object({userId:z26.string().min(1),name:z26.string(),email:z26.string().min(1),subscribed:z26.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z26.object({maxSubscribers:z26.number().int().positive(),subscriberCount:z26.number().int().nonnegative(),effectiveRecipientCount:z26.number().int().nonnegative(),currentUserSubscribed:z26.boolean(),candidates:z26.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z26.object({userIds:z26.array(z26.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z26.object({topic:UserManagedNotificationTopicSchema,enabled:z26.boolean(),source:z26.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z26.object({topics:z26.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z26.object({enabled:z26.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z26.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z26.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z26.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z26.string().nullable(),maskedEmail:z26.string().min(1),applied:z26.boolean(),expiresAt:z26.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z26.object({scheduleId:z26.string().min(1),scheduleName:z26.string(),projectId:z26.string().min(1),projectName:z26.string(),env:z26.string().min(1)}),FollowedSchedulesSchema=z26.object({schedules:z26.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z27}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z27.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z27.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z27.uuid(),env:z27.string().min(1),name:z27.string().min(1),cron:z27.string().min(1),command:z27.string().min(1),secretKeys:z27.array(z27.string().min(1)),enabled:z27.boolean(),lastRunAt:z27.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z27.string().nullable(),overPolicyReasons:z27.array(z27.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120),cron:z27.string().min(1).max(120),command:z27.string().min(1).max(500),secretKeys:z27.array(ProjectSecretKeySchema).default([]),enabled:z27.boolean().optional()}),UpdateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120).optional(),cron:z27.string().min(1).max(120).optional(),command:z27.string().min(1).max(500).optional(),secretKeys:z27.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z27.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z27.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z27.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z27.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z27.object({maxRuns:z27.number().int().positive(),retentionDays:z27.number().int().positive().nullable(),outputRetentionDays:z27.number().int().positive(),maxOutputBytes:z27.number().int().positive()}),SchedulePolicyStateSchema=z27.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z27.object({code:z27.enum(["Free","Premium"]),source:z27.enum(["cached_subscription","free_fallback"]),activeSchedules:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),concurrency:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),compute:z27.object({settledMs:z27.number().int().nonnegative(),reservedMs:z27.number().int().nonnegative(),includedMs:z27.number().int().positive(),remainingMs:z27.number().int().nonnegative(),resetsAt:z27.coerce.date()}),upgrade:z27.object({code:z27.literal("Premium"),activeSchedulesLimit:z27.number().int().positive(),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),maxConcurrentRuns:z27.number().int().positive(),computeIncludedMs:z27.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z27.array(z27.string())}),ProjectScheduleUsageSchema=z27.object({runCount:z27.number().int().nonnegative(),runsWithOutput:z27.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z27.object({id:z27.uuid(),scheduleId:z27.uuid(),projectId:z27.uuid(),env:z27.string().min(1),scheduleName:z27.string().min(1),command:z27.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z27.object({id:z27.string().min(1),name:z27.string().min(1)}).nullable(),queuedAt:z27.coerce.date(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),exitCode:z27.number().int().nullable(),errorCode:z27.string().nullable(),error:z27.string().nullable(),outputBytes:z27.number().int().nonnegative(),outputTruncated:z27.boolean(),outputExpiresAt:z27.coerce.date().nullable(),metadataExpiresAt:z27.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z27.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z27.coerce.date().nullable(),items:z27.array(z27.object({key:z27.string().min(1),updatedAt:z27.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z27.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z27.object({trigger:z27.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z27.object({limit:z27.coerce.number().int().min(1).max(100).default(25),cursor:z27.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z27.object({items:z27.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z27.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z27.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z27.object({items:z27.array(ProjectScheduleRunDTOSchema),nextCursor:z27.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z28}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z28.object({id:z28.uuid(),occurredAt:z28.coerce.date(),projectId:z28.uuid().nullable(),env:z28.string().nullable(),actor:z28.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z28.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z28.unknown().optional(),ipAddress:z28.string().nullable().optional(),userAgent:z28.string().nullable().optional(),error:z28.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z28.object({rows:z28.array(AuditLogRowDTOSchema),nextCursor:z28.string().nullable()})),AuditLogQuerySchema=z28.object({env:z28.string().optional(),action:AuditActionSchema.optional(),actor:z28.string().optional(),from:z28.coerce.date().optional(),to:z28.coerce.date().optional(),limit:z28.coerce.number().int().min(1).max(200).optional(),cursor:z28.string().optional()})}});import{z as z29}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z29.object({surface:SurfaceNameSchema,key:z29.string(),label:z29.string()}),InlineSchema=z29.object({text:z29.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z29.discriminatedUnion("type",[z29.object({type:z29.literal("paragraph"),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("preview"),ref:DiffRefSchema,caption:z29.string().optional()}),z29.object({type:z29.literal("code"),code:z29.string(),lang:z29.string().optional(),caption:z29.string().optional()}),z29.object({type:z29.literal("risk"),level:z29.enum(["warning","error"]),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("list"),items:z29.array(z29.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z29.object({headline:z29.string(),blocks:z29.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z29.object({summary:EnvDiffSummarySchema,fingerprint:z29.string(),generatedAt:z29.coerce.date(),cached:z29.boolean().optional(),credits:z29.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z30}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z30.object({date:z30.string(),visitors:z30.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z30.object({key:z30.string(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z30.object({path:z30.string(),pageName:z30.string().nullable().optional(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z30.object({preset:z30.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z30.string(),requestedTo:z30.string(),effectiveFrom:z30.string(),effectiveTo:z30.string(),isRetentionLimited:z30.boolean(),groupBy:z30.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z30.object({date:z30.string(),content:z30.string(),updatedAt:z30.string(),updatedByUserId:z30.string()}),ProjectPageviewAnalyticsDTOSchema=z30.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative(),bounceRate:z30.number().min(0).max(100),viewsPerVisit:z30.number().nonnegative(),averageVisitDurationSeconds:z30.number().nonnegative(),visitorsSeries:z30.array(ProjectDailyVisitorsDTOSchema),topPages:z30.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z30.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z31}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z31.object({id:z31.string(),email:z31.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z31.coerce.date(),createdAt:z31.coerce.date(),inviterUserId:z31.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z31.object({id:z31.string(),token:z31.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z31.object({success:z31.boolean(),projectId:z31.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z32}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z32.object({id:z32.string(),name:z32.string(),image:z32.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z32.object({count:z32.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z32.object({counts:z32.object({signed_up:z32.int(),activated:z32.int()}),credits:z32.object({total:z32.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z32.email(),emailVerified:z32.boolean(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z33}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z33.object({id:z33.string(),principalType:ProjectPrincipalTypeSchema,principalId:z33.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z33.coerce.date(),expiresAt:z33.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z33.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z33.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z33.record(z33.string(),z33.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z33.object({access:z33.array(ProjectAccessItemDTOSchema),invites:z33.array(ProjectInviteDTOSchema),organization:z33.object({name:z33.string().nullable(),logo:z33.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z33.object({success:z33.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z33.object({success:z33.boolean(),projectId:z33.uuid()}))}});import{z as z34}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z34.object({publicationStatus:PublicationStatusSchema,appUrl:z34.string().nullable(),lastPublishedAt:z34.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z35}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z35.object({url:z35.url(),expiresAt:z35.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z36}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z36.string(),slug:z36.string().nullable(),logo:z36.string().nullable(),metadata:z36.record(z36.string(),z36.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z36.object({id:z36.string(),name:z36.string(),email:z36.email(),image:z36.string().nullable()}),OrganizationMemberDTOSchema=z36.object({id:z36.string(),userId:z36.string(),organizationId:z36.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z36.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z37}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z37.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z37.object({reason:CancellationReasonCodeSchema,details:z37.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z37.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z37.object({included:z37.number().optional(),unitPrice:z37.number().optional(),dailyCap:z37.number().nullable().optional()}),EntitlementsDTOSchema=z37.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z37.object({retentionDays:z37.number().int().positive(),canUseExtendedDateRanges:z37.boolean()}).optional(),history:z37.object({retentionDays:z37.number().int().positive()}).optional(),members:z37.object({canInvite:z37.boolean(),maxMembers:z37.number().int().positive().nullable()}).optional(),domains:z37.object({canUseCustomDomains:z37.boolean(),maxDomains:z37.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z37.object({id:z37.string(),external_id:z37.string(),customerId:z37.string(),planId:z37.string(),planCode:TemplateCodeSchema,currentPeriod:z37.object({start:z37.string(),end:z37.string().nullable()}),cancelAt:z37.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z37.string(),nextPaymentAt:z37.string().nullable(),baseAmount:z37.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z37.object({totalCap:z37.number(),dailyCap:z37.number(),usedTotal:z37.number()}),CreditBalanceDTOSchema=z37.object({total:z37.number(),base:z37.number(),dailyBase:z37.number(),purchases:z37.number(),awards:z37.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z37.object({total:z37.number(),nearLimit:z37.boolean(),canChat:z37.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z37.object({dailyFreeAvailable:z37.number(),monthlyAvailable:z37.number(),purchasedAvailable:z37.number(),awardedAvailable:z37.number()}),ProjectDailyCreditAllowanceDTOSchema=z37.object({periodCap:z37.number(),dailyGrant:z37.number(),usedThisPeriod:z37.number(),remainingThisPeriod:z37.number()}),ProjectCreditBalanceDTOSchema=z37.object({projectId:z37.uuid(),organizationId:z37.string(),balance:z37.object({totalAvailable:z37.number(),nearLimit:z37.boolean(),canUseAi:z37.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z37.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().nonnegative(),refillAmountUsd:z37.number().nonnegative()}),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().nonnegative().nullable(),refillAmountUsd:z37.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().min(.01).multipleOf(.01),refillAmountUsd:z37.number().min(.01).multipleOf(.01)}).strict(),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z37.object({invoiceId:z37.string(),newBalance:z37.int(),creditCount:z37.int(),amountUsd:z37.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z37.object({url:z37.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z38}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z38.object({brand:z38.string(),last4:z38.string(),exp:z38.string(),isDefault:z38.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z39}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z39.string().superRefine((path49,ctx)=>{let segments=path49.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z39.object({type:z39.literal("renameField"),contentType:z39.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z39.object({enabled:z39.boolean()}).strict(),ContentTypeDTOSchema=z39.object({id:z39.string(),name:z39.string(),label:z39.string(),isSingleton:z39.boolean(),i18n:ContentTypeI18nSchema,fields:z39.record(z39.string(),FieldDefinitionSchema),createdAt:z39.string(),updatedAt:z39.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z39.object({contentTypes:z39.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z39.object({id:z39.string(),entryId:z39.string(),documentId:z39.string(),slug:z39.string(),locale:z39.string().optional(),createdAt:z39.string(),updatedAt:z39.string(),__fimo:z39.object({contentType:z39.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({limit:z39.number(),offset:z39.number(),total:z39.number(),hasMore:z39.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z39.object({contentType:z39.string(),count:z39.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z39.object({counts:z39.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z39.object({count:z39.number().int().nonnegative(),sourceLocale:z39.string(),targetLocale:z39.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z39.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z39.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z39.union([z39.string(),z39.number(),z39.boolean(),z39.null()]),entryWhereOperatorSchema=z39.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z39.array(entryWhereScalarSchema).optional(),$nin:z39.array(entryWhereScalarSchema).optional(),$contains:z39.string().optional(),$startsWith:z39.string().optional(),$null:z39.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z39.object({data:z39.record(z39.string(),z39.unknown()),locale:z39.string().min(1).optional(),documentId:z39.uuid().optional()}),entryIdsSchema=z39.array(z39.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z39.object({sql:z39.string().min(1)}),BulkCreateEntriesRequestSchema=z39.object({entries:z39.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z39.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z39.object({updates:z39.array(z39.object({id:z39.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,locale:z39.string().min(1).optional()}),z39.object({where:EntryWhereSchema,locale:z39.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z39.object({data:z39.array(z39.record(z39.string(),z39.unknown())),meta:z39.object({rowCount:z39.number().int().nonnegative(),truncated:z39.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({created:z39.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({updated:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({deleted:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z40}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z40.object({index:z40.number().int().nonnegative(),contentType:z40.string(),field:z40.string(),value:z40.string(),against:z40.enum(["stored","batch"]),ownerDocumentId:z40.uuid().optional(),ownerIndex:z40.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z40.object({code:z40.literal("unique_conflict"),message:z40.string(),conflicts:z40.array(UniqueConflictSchema),truncated:z40.boolean().optional()})}});import{z as z41}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z41.object({kind:z41.literal("unique_conflict"),contentType:z41.string(),field:z41.string(),value:z41.string(),documentCount:z41.number().int().positive(),documentIds:z41.array(z41.uuid()),documentIdsTruncated:z41.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z41.object({code:z41.literal("schema_transition_rejected"),message:z41.string(),issues:z41.array(SchemaTransitionIssueSchema),truncated:z41.boolean().optional()})}});import{z as z42}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z42.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z42.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z42.object({field:CmsFieldNameSchema,direction:z42.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z42.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z42.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z42.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z42.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z42.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z43}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z43.object({id:z43.string(),name:z43.string()}),AssetDTOSchema=z43.object({id:z43.string(),name:z43.string(),type:AssetTypeSchema,originalFileName:z43.string().nullable(),parentId:z43.string().nullable(),mimeType:z43.string().nullable(),fileSize:z43.number().nullable(),url:z43.string().nullable(),storageKey:z43.string().nullable(),createdAt:z43.string(),updatedAt:z43.string(),altText:z43.string().nullable().optional(),caption:z43.string().nullable().optional(),aiCaption:z43.string().nullable().optional(),aiAltText:z43.string().nullable().optional(),aiTags:z43.array(z43.string()).nullable().optional(),aiPrimaryColor:z43.string().nullable().optional(),aiProcessingStatus:z43.string().nullable().optional(),width:z43.number().nullable().optional(),height:z43.number().nullable().optional(),path:z43.array(AssetPathItemSchema).optional(),hasChildren:z43.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z43.lazy(()=>z43.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z43.array(AssetDTOSchema))}});import{z as z44}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z44.object({key:z44.string(),value:z44.string().optional(),defaultValue:z44.string(),locale:z44.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z45}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z45.object({id:z45.string(),name:z45.string(),type:z45.enum(["file","folder"]),path:z45.string(),children:z45.lazy(()=>z45.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z45.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z45.object({path:z45.string(),exists:z45.boolean(),type:z45.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z46}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z46.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z46.object({items:z46.array(ProjectMessagePublicDTOSchema),nextCursor:z46.string().nullable()}),ChatLiveTurnDTOSchema=z46.object({invocationId:z46.string(),step:z46.enum(["preparing","working","compacting","merging"]),startedAt:z46.string()}),ChatLiveTurnStateDTOSchema=z46.object({threadId:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z46.object({id:z46.string(),role:z46.enum(["user","assistant"]),parts:z46.array(z46.unknown()),metadata:z46.record(z46.string(),z46.unknown()).nullable(),versionId:z46.string().nullable().optional(),createdAt:z46.date().transform(value=>value.toISOString()),providerMessageId:z46.string().nullable().optional(),invocationId:z46.string().nullable().optional(),invocationStatus:z46.string().nullable().optional(),invocationTerminalReason:z46.string().nullable().optional()}),ChatAttentionDTOSchema=z46.object({type:z46.literal("merge_conflict"),merge:z46.object({mergeId:z46.string().uuid(),projectId:z46.string(),fromEnv:z46.string(),toEnv:z46.string()}),publishAfterMerge:z46.boolean()}),ChatThreadMessagesPageDTOSchema=z46.object({threadId:z46.string().nullable(),title:z46.string().nullable(),messages:z46.array(ChatThreadMessageDTOSchema),nextCursor:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z46.object({kind:z46.literal("replay"),threadId:z46.string(),userMessageId:z46.string()}),ChatQueuedOutcomeDTOSchema=z46.object({kind:z46.literal("queued"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string()}),ChatBusyOutcomeDTOSchema=z46.object({kind:z46.literal("busy"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string().optional()}),ChatRefusedOutcomeDTOSchema=z46.object({kind:z46.literal("refused"),threadId:z46.string(),userMessageId:z46.string(),refusedInvocationId:z46.string(),terminalReason:z46.string()}),ChatNonStreamingOutcomeDTOSchema=z46.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z46.object({success:z46.boolean(),deletedCount:z46.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z46.object({code:z46.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z46.string()})}});import{z as z47}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z47.object({url:z47.string().url(),key:z47.string(),size:z47.number(),contentType:z47.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z48}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z48.object({canAccess:z48.boolean(),permissions:z48.record(z48.string(),z48.boolean()),role:z48.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z49}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z49.string().trim().default(""),sort:z49.enum(["recent","name","relevance"]).default("recent"),category:z49.string().optional()})}});import{z as z50}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z50.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z50.enum(["fimo","external"]),PaymentStatusSchema=z50.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z50.object({id:z50.string().uuid(),domain:z50.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z50.boolean(),price:z50.number().int().nullable(),renewalPrice:z50.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z50.string().nullable(),failureReason:z50.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z50.object({domain:z50.string(),available:z50.boolean(),premium:z50.boolean(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),purchaseType:z50.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z50.object({domain:z50.string(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),premium:z50.boolean(),allowedYears:z50.array(z50.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z50.object({firstName:z50.string().max(100),lastName:z50.string().max(100),companyName:z50.string().max(100).optional(),address1:z50.string().max(255),address2:z50.string().max(255).optional(),city:z50.string().max(100),state:z50.string().max(100),zip:z50.string().max(20),country:z50.string().max(2),phone:z50.string().max(30),email:z50.union([z50.string().email().max(255),z50.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z50.object({firstName:z50.string().min(1).max(100),lastName:z50.string().min(1).max(100),companyName:z50.string().max(100).optional(),address1:z50.string().min(1).max(255),address2:z50.string().max(255).optional(),city:z50.string().min(1).max(100),state:z50.string().min(1).max(100),zip:z50.string().min(1).max(20),country:z50.string().min(1).max(2),phone:z50.string().min(1).max(30),email:z50.string().email().max(255)}),SearchDomainsRequestSchema=z50.object({keyword:z50.string().min(1).max(100),tldFilter:z50.array(z50.string()).optional()}),CheckAvailabilityRequestSchema=z50.object({domains:z50.array(z50.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z50.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z50.object({domain:DomainNameSchema,years:z50.number().int().min(1).max(10).optional().default(3),autoRenew:z50.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z50.object({autoRenew:z50.boolean().optional()}),RenewDomainRequestSchema=z50.object({years:z50.number().int().min(1).max(10).optional().default(1),autoRenew:z50.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z50.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z50.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z50.object({verified:z50.boolean(),email:z50.string().nullable(),verifyBy:z50.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z51}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z51.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z51.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z51.object({txtName:z51.string().nullable().optional(),txtValue:z51.string().nullable().optional(),httpUrl:z51.string().nullable().optional(),httpBody:z51.string().nullable().optional(),cname:z51.string().nullable().optional(),cnameTarget:z51.string().nullable().optional()}),SSLValidationErrorSchema=z51.object({message:z51.string()}),OwnershipVerificationSchema=z51.object({type:z51.string(),name:z51.string(),value:z51.string()}),ProjectDomainSSLDTOSchema=z51.object({status:z51.string(),method:z51.string().nullable(),type:z51.string().nullable(),validationRecords:z51.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z51.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z51.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z51.enum(["subdomain","apex"]),RedirectConfigSchema=z51.object({type:z51.literal("apex_to_www"),linkedDomainId:z51.string()}).nullable().optional(),ProjectDomainDTOSchema=z51.object({id:z51.string(),hostname:z51.string(),status:z51.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z51.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z51.string(),scdCnameTarget:z51.string().optional(),apexTargets:z51.array(z51.string()),dnsAutoConfigured:z51.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z51.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z51.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z51.object({hostname:z51.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z51.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z51.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z51.object({available:z51.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z51.object({success:z51.boolean(),hostname:z51.string()}))}});import{z as z52}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z52.object({available:z52.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z52.object({slug:z52.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z52.object({subdomain:z52.string(),subdomainUpdatedAt:z52.coerce.date()})),SubdomainSuggestionsQuerySchema=z52.object({base:z52.string().max(100).optional(),max:z52.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z52.object({suggestions:z52.array(z52.string())}))}});import{z as z53}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z53.object({translated:z53.number().int().nonnegative(),total:z53.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z53.object({locale:z53.string(),isDefault:z53.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z53.object({defaultLocale:z53.string(),locales:z53.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z53.object({locale:z53.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z53.object({locale:z53.string().min(1).max(40)}),ProjectLocaleMutationSchema=z53.object({locale:z53.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z53.object({locale:z53.string(),entriesDeleted:z53.number().int().nonnegative(),labelsDeleted:z53.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z54}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z54.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z54.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z54.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z54.number(),credits:z54.number().optional(),billingMode:z54.enum(["fimo-credits","provider-account"]).optional(),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z55}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z55.object({options:z55.record(z55.string(),z55.unknown()),name:z55.string().optional(),parentId:z55.string().nullable().optional(),altText:z55.string().optional(),caption:z55.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z55.string().min(1).optional(),model:z55.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z55.object({jobId:z55.string(),status:z55.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z55.string().nullable().optional(),credits:z55.number().optional(),costUsd:z55.number().optional(),billingMode:z55.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z55.object({error:z55.string(),code:z55.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z55.array(GenerationTaskIdSchema).optional(),availableModels:z55.array(z55.string()).optional(),issues:z55.array(z55.unknown()).optional()})}});import{z as z56}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z56.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z56.object({name:z56.string(),key:z56.string(),description:z56.string(),type:FlagTypeSchema,required:z56.boolean(),defaultValue:z56.unknown().optional(),enumValues:z56.array(z56.string()).optional(),isArray:z56.boolean()}),AssetModelPriceSchema=z56.object({unitPrice:z56.number(),unit:z56.string(),confidence:z56.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z56.object({id:z56.string(),shortName:z56.string(),provider:z56.string(),source:z56.string(),modality:z56.enum(["image","video","audio"]),tags:z56.array(z56.string()),displayName:z56.string(),description:z56.string(),flags:z56.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z56.object({model:z56.string(),costUsd:z56.number(),credits:z56.number(),billingMode:z56.enum(["fimo-credits","provider-account"]),confidence:z56.enum(["exact","estimated","metered"]),basis:z56.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z57}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z57.object({tourId:z57.string(),version:z57.string(),status:z57.string(),completedAt:z57.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z57.array(UserTourDTOSchema))}});import{z as z58}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z58.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z58.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z58.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z58.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z58.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z58.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z58.enum(["user","agent","system"]),SupportReportTagSchema=z58.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z58.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z58.object({organization:z58.object({id:z58.string().trim().min(1).max(255),name:z58.string().trim().max(240).optional()}),project:z58.object({id:z58.uuid(),name:z58.string().trim().max(240).optional(),createdAt:z58.coerce.date().optional()}).optional(),environment:z58.string().trim().max(255).optional(),clientVersion:z58.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z58.string().trim().max(200).optional(),limit:z58.coerce.number().int().min(1).max(100).default(50),offset:z58.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z58.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z58.uuid().nullable().optional(),note:z58.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z58.object({kind:SupportReportLinkKindSchema,label:z58.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z58.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z58.object({kind:SupportReportActorKindSchema,id:z58.string().nullable(),name:z58.string().nullable()}),SupportReportLinkDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportLinkKindSchema,label:z58.string(),url:SupportReportHttpUrlSchema,externalId:z58.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportEventKindSchema,body:z58.string().nullable(),metadata:z58.record(z58.string(),z58.unknown()),actor:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z58.object({id:z58.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z58.array(z58.string()),source:SupportReportSourceSchema,message:z58.string(),reporter:z58.object({id:z58.string().nullable(),name:z58.string().nullable(),email:z58.string().nullable()}),organization:z58.object({id:z58.string().nullable(),name:z58.string()}),project:z58.object({id:z58.uuid().nullable(),name:z58.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z58.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z58.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}).nullable(),duplicateOfReportId:z58.uuid().nullable(),resolvedAt:z58.coerce.date().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z58.string().nullable(),clientVersion:z58.string().nullable(),links:z58.array(SupportReportLinkDTOSchema),events:z58.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z58.object({reports:z58.array(SupportReportSummaryDTOSchema),total:z58.number().int().nonnegative(),statusCounts:z58.object({new:z58.number().int().nonnegative(),in_progress:z58.number().int().nonnegative(),waiting:z58.number().int().nonnegative(),resolved:z58.number().int().nonnegative(),duplicate:z58.number().int().nonnegative(),irrelevant:z58.number().int().nonnegative(),ignored:z58.number().int().nonnegative()}),limit:z58.number().int().positive(),offset:z58.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z58.object({id:z58.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z58.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z59}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z59.iso.datetime({offset:!0}).pipe(z59.coerce.date()),OpsRecentChatInputSchema=z59.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z59.string().trim().min(1).max(255).optional(),limit:z59.coerce.number().int().min(1).max(200).default(100),cursor:z59.string().trim().min(1).max(2e3).optional(),slim:z59.boolean().default(!0),reason:z59.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z59.object({id:z59.string(),threadId:z59.string(),providerMessageId:z59.string().nullable(),invocationId:z59.string().nullable(),env:z59.string().nullable(),role:z59.string(),parts:z59.array(z59.record(z59.string(),z59.unknown())),metadata:z59.object({status:z59.string().optional(),traceUrl:z59.string().optional(),externalFileChanges:z59.array(z59.unknown()).optional()}),stats:z59.object({toolCount:z59.number().int().nonnegative(),failedToolCount:z59.number().int().nonnegative()}),createdAt:z59.iso.datetime({offset:!0}),project:z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),organizationId:z59.string().nullable()})}),OpsRecentChatResponseSchema=z59.object({target:z59.object({backendProfile:OpsBackendProfileSchema,projectEnv:z59.string().nullable()}),window:z59.object({from:z59.iso.datetime({offset:!0}),to:z59.iso.datetime({offset:!0})}),messages:z59.object({items:z59.array(OpsRecentChatMessageSchema),nextCursor:z59.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z60}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z60.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z60.literal(!1),reason:z60.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z61}from"zod";function createAgentRunWebhookEventDataSchema(status){return z61.object({run:z61.object({id:z61.string(),agentName:z61.string(),trigger:z61.string(),status:z61.literal(status),startedAt:z61.string().nullable(),finishedAt:z61.string().nullable(),reason:z61.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z61.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z61.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z61.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z61.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z61.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z61.union([z61.literal(0),z61.literal(5),z61.literal(30),z61.literal(60)]),EntryChangedWebhookEventDataSchema=z61.object({reason:WebhookEntryChangeReasonSchema,operationId:z61.string().optional(),batch:z61.object({index:z61.number().int().positive(),total:z61.number().int().positive()}).optional(),changes:z61.array(z61.object({action:WebhookEntryChangeActionSchema,contentType:z61.string(),id:z61.string(),documentId:z61.string(),locale:z61.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z61.object({form:z61.object({id:z61.string(),label:z61.string()}),submission:z61.object({id:z61.string(),data:z61.record(z61.string(),z61.unknown()),submittedAt:z61.string()})}),PublishStartedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("publishing"),startedAt:z61.string()})}),PublishSucceededWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("published"),url:z61.string(),publishedAt:z61.string(),firstPublish:z61.boolean()})}),PublishFailedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("failed"),reason:z61.string()})}),PublishUnpublishedWebhookEventDataSchema=z61.object({publication:z61.object({previousUrl:z61.string(),unpublishedAt:z61.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),classification:z61.string(),summary:z61.string(),reasons:z61.array(z61.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),resolution:z61.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z61.object({report:z61.object({weekStart:z61.string(),weekEnd:z61.string(),pageviews:z61.number(),visitors:z61.number(),previousPageviews:z61.number(),previousVisitors:z61.number()})}),MediaAssetWebhookEventDataSchema=z61.object({id:z61.string().nullable(),name:z61.string().nullable(),type:z61.string(),mimeType:z61.string().nullable(),fileSize:z61.number().nullable()}),MediaUploadedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["updated","moved","analysis"]),analysis:z61.object({category:z61.string(),status:z61.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("generated"),generation:z61.object({model:z61.string(),mode:z61.string()})}),MediaProcessingFailedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["analysis","generation"]),failure:z61.object({code:z61.string()})}),DomainCreatedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string()})}),LabelChangedWebhookEventDataSchema=z61.object({changes:z61.array(z61.object({action:z61.enum(["created","updated","deleted"]),key:z61.string(),locale:z61.string(),value:z61.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),isDefault:z61.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),previousCode:z61.string()})}),LocaleDeletedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),entriesDeleted:z61.number().int().nonnegative(),labelsDeleted:z61.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z61.object({merge:z61.object({id:z61.string(),from:EnvSchema,to:EnvSchema,applied:z61.array(z61.object({surface:SurfaceNameSchema,count:z61.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema}),version:z61.object({versionId:z61.uuid(),name:z61.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z61.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z61.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z61.discriminatedUnion("source",[z61.object({source:z61.literal("literal"),value:z61.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z61.object({source:z61.literal("secret"),key:z61.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z61.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z61.object({name:z61.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z61.object({name:z61.string(),source:z61.enum(["literal","secret"]),secretKey:z61.string().nullable(),secretPrefix:z61.string().nullable(),configured:z61.literal(!0)}),WebhookFilterSchema=z61.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z61.string().min(1).max(255).optional(),agentName:z61.string().min(1).max(120).optional(),mediaType:z61.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z61.string().min(1).max(255).optional(),locale:z61.string().min(1).max(120).optional()}),JsonValueSchema=z61.lazy(()=>z61.union([z61.string(),z61.number(),z61.boolean(),z61.null(),z61.array(JsonValueSchema),z61.record(z61.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z61.url(),enabled:z61.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z61.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z61.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z61.url().optional(),enabled:z61.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z61.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z61.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z61.object({eventType:WebhookEventTypeSchema.optional(),data:z61.record(z61.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z61.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z61.uuid(),name:z61.string(),eventType:WebhookEventTypeSchema,enabled:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z61.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z61.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z61.coerce.date().nullable(),deliveryStats24h:z61.object({succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z61.uuid(),projectId:z61.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z61.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z61.number().int().positive(),test:z61.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z61.number().int().nonnegative(),responseStatus:z61.number().int().nullable(),lastErrorCode:z61.string().nullable(),lastErrorMessage:z61.string().nullable(),payloadAvailable:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z61.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z61.string().nullable(),qstashMessageId:z61.string().nullable(),deliveredAt:z61.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z61.object({items:z61.array(WebhookDeliveryDTOSchema),pagination:z61.object({page:z61.number().int().positive(),limit:z61.number().int().positive(),total:z61.number().int().nonnegative(),totalPages:z61.number().int().positive(),hasMore:z61.boolean()}),stats:z61.object({total:z61.number().int().nonnegative(),succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z61.object({id:z61.uuid(),deliveryId:z61.uuid(),attempt:z61.number().int().positive(),status:z61.enum(["delivering","succeeded","failed"]),responseStatus:z61.number().int().nullable(),durationMs:z61.number().int().nonnegative(),responseExcerpt:z61.string().nullable(),errorCode:z61.string().nullable(),errorMessage:z61.string().nullable(),createdAt:z61.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z61.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z61.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z62}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z62.object({key:z62.literal("fimo-2"),enabled:z62.boolean(),dismissed:z62.boolean().default(!1),interacted:z62.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z63}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z63.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z63.object({total:z63.number(),base:z63.number(),purchases:z63.number(),awards:z63.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z63.object({id:z63.string(),name:z63.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z63.object({type:z63.string(),brand:z63.string().nullable(),last4:z63.string().nullable(),expirationDate:z63.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z63.object({currency:z63.string(),nextPaymentAmount:z63.number().nullable(),nextPaymentAt:z63.string().nullable(),billingInterval:z63.string().nullable(),totalAmount:z63.number().nullable(),discountAmount:z63.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z63.object({id:z63.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z63.string().nullable(),currentPeriodEndsAt:z63.string().nullable(),renewsAt:z63.string().nullable(),cancelAt:z63.string().nullable(),renewAutomatically:z63.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z63.object({type:z63.enum(["low_balance","critical_balance","approaching_limit"]),message:z63.string(),estimatedPromptsRemaining:z63.number().nullable(),avgCostPerPrompt:z63.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z63.object({monthlyCredits:z63.number().nullable(),usedThisPeriod:z63.number(),remainingThisPeriod:z63.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z63.object({organizationId:z63.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z63.string().nullable(),tenureDays:z63.number().int().nonnegative(),capturedAt:z63.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z63.object({hasSubscription:z63.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z63.number().nullable(),alerts:z63.array(CreditAlertDTOSchema),portalUrl:z63.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z63.object({creditCount:z63.number().int().positive(),expiresAt:z63.string().datetime().nullable().optional(),message:z63.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("free"),amountCents:z63.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("purchase"),amountCents:z63.number().int().positive()}),CreditTopupRequestDTOSchema=z63.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z63.object({success:z63.boolean(),transactionId:z63.string().nullable(),newBalance:z63.number(),creditCount:z63.number(),type:z63.enum(["free","purchase"]),invoiceId:z63.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z64}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z64.object({totalCredits:z64.number(),totalCostUsd:z64.number(),totalMessages:z64.number(),avgCostPerMessage:z64.number(),periodStart:z64.string().nullable(),periodEnd:z64.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z64.object({date:z64.string(),credits:z64.number(),costUsd:z64.number(),messages:z64.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z64.array(UsageByUserForProjectDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z64.object({summary:UsageSummaryDTOSchema,byProject:z64.array(UsageByProjectDTOSchema),byUser:z64.array(UsageByUserDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z65}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z65.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z65.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z65.object({startDate:z65.string().optional(),endDate:z65.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z65.coerce.number().int().positive().default(1),limit:z65.coerce.number().int().positive().max(100).default(20),sortBy:z65.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z65.string().optional(),activeOnly:z65.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z65.object({totalCredits:z65.number(),totalCostUsd:z65.number(),totalMessages:z65.number(),avgCostPerMessage:z65.number(),avgCreditsPerMessage:z65.number(),periodStart:z65.string(),periodEnd:z65.string(),creditsChange:z65.number().nullable(),costChange:z65.number().nullable(),messagesChange:z65.number().nullable(),unattributedCredits:z65.number(),unattributedCostUsd:z65.number(),unattributedMessages:z65.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z65.object({date:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z65.object({organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number(),projectCount:z65.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z65.object({userId:z65.string(),userName:z65.string().nullable(),userEmail:z65.string().nullable(),userImage:z65.string().nullable(),organizationId:z65.string().nullable(),organizationName:z65.string().nullable(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),projectCount:z65.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z65.object({projectId:z65.string(),projectName:z65.string(),projectDisplayName:z65.string().nullable(),organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z65.object({id:z65.string(),name:z65.string(),value:z65.number(),percentage:z65.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z65.object({day:z65.number(),hour:z65.number(),value:z65.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z65.object({summary:UsageOverviewSummaryDTOSchema,timeline:z65.array(UsageTimelinePointDTOSchema),topOrganizations:z65.array(OrganizationUsageRowDTOSchema),topUsers:z65.array(UserUsageRowDTOSchema),topProjects:z65.array(ProjectUsageRowDTOSchema),creditDistribution:z65.array(UsageDistributionItemDTOSchema),userDistribution:z65.array(UsageDistributionItemDTOSchema),heatmap:z65.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z65.object({page:z65.number(),limit:z65.number(),totalItems:z65.number(),totalPages:z65.number(),hasMore:z65.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z65.object({organizations:z65.array(OrganizationUsageRowDTOSchema),top:z65.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z65.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z65.object({users:z65.array(ExtendedUserUsageRowDTOSchema),top:z65.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z65.object({projects:z65.array(ExtendedProjectUsageRowDTOSchema),top:z65.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z65.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z65.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z65.object({credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),createdAt:z65.string(),memberCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z65.object({id:z65.string(),name:z65.string().nullable(),email:z65.string(),image:z65.string().nullable(),createdAt:z65.string(),organizationCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),createdAt:z65.string(),organizationId:z65.string(),organizationName:z65.string(),ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z66}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z66.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z66.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z66.object({command:z66.string().min(1).max(1e4),cwd:z66.string().optional(),projectEnv:EnvSchema.optional(),env:z66.record(z66.string(),z66.string()).optional(),name:z66.string().optional(),waitForCompletion:z66.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z66.object({identifier:z66.string(),status:SandboxProcessStatusSchema,command:z66.string().optional(),startedAt:z66.string().optional(),exitCode:z66.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z66.object({processes:z66.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z66.object({processId:z66.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z66.object({success:z66.boolean(),message:z66.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z67}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}cfg;static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path49,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers})}async rawRequest(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path49} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentEnvs&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listEnvs(projectId,{includeAgentEnvs:!0}),current=branches.find(candidate=>candidate.env===branch),visited=new Set;for(;current&&!visited.has(current.env);){if(visited.add(current.env),current.resolvedEnvironment)return current.resolvedEnvironment.id;current=current.parentEnv?branches.find(candidate=>candidate.env===current?.parentEnv):void 0}return PREVIEW_ENVIRONMENT_KEY}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path49,opts={}){let qs=lazyFetchQs(opts.against,{path:path49});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.env&¶ms.set("env",opts.env),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
42
|
+
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue2=data2[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});import{z as z6}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z6.union([z6.literal(PRODUCTION_ENVIRONMENT_KEY),z6.literal(PREVIEW_ENVIRONMENT_KEY),z6.uuid()]),CustomEnvironmentSchema=z6.object({id:z6.uuid(),projectId:z6.uuid(),name:z6.string().trim().min(1).max(64),branchPatterns:z6.array(z6.string().min(1).max(255)).min(1),description:z6.string().max(255).nullable()}),ResolvedEnvironmentSchema=z6.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});import{z as z7}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z7.preprocess(referenceValuePreprocess,z7.object({documentId:z7.uuid()})),ReferenceInputValueSchema=z7.preprocess(referenceValuePreprocess,z7.union([z7.object({documentId:z7.uuid()}),z7.object({slug:z7.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.object({contentType:z7.string().min(1),documentId:z7.uuid()})),PolymorphicReferenceInputValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.union([z7.object({contentType:z7.string().min(1),documentId:z7.uuid()}),z7.object({contentType:z7.string().min(1),slug:z7.string().min(1)})]))}});import{z as z8}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path49){let conditionPath=[...path49,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,path49)=>{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,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z8.union([z8.object({field:z8.string().min(1),equals:z8.union([z8.string(),z8.number(),z8.boolean()])}).strict(),z8.object({field:z8.string().min(1),in:z8.array(z8.union([z8.string(),z8.number(),z8.boolean()])).min(1)}).strict()]),commonFieldShape={label:z8.string().min(1).optional(),description:z8.string().optional(),editable:z8.boolean().optional(),required:z8.boolean().optional(),default:z8.unknown().optional(),showIf:z8.union([showIfClauseSchema,z8.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z8.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z8.object({...commonFieldShape,type:z8.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z8.number().optional(),max:z8.number().optional(),minLength:z8.number().int().nonnegative().optional(),maxLength:z8.number().int().nonnegative().optional(),regex:z8.string().optional(),multiple:z8.boolean().optional(),allowedMimeTypes:z8.array(z8.string()).optional(),options:z8.array(z8.string().min(1)).min(1).optional(),unique:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z8.object({...commonFieldShape,type:z8.literal("reference"),target:z8.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z8.array(z8.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z8.boolean().optional(),i18n:z8.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z8.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z8.record(z8.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z8.object({uid:z8.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z8.string().min(1),description:z8.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z8.object({fields:blockFieldsSchema}).strict(),blocksSchema=z8.object({oneOf:z8.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z8.object({...commonFieldShape,type:z8.literal("blocks"),min:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z8.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z8.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z9}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z9.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z9.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z9.enum(AUDIT_ACTOR_KINDS)}});import{z as z10}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z10.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z10.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z10.object({permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),enabled:z10.boolean().default(!0)}),OpsServiceTokenInputSchema=z10.object({name:z10.string().trim().min(1).max(120),permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),expiresAt:z10.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z10.object({importanceReason:z10.string().trim().min(1).max(1e3),ownerUserId:z10.string().trim().min(1).nullable().optional(),framework:z10.string().trim().max(120).nullable().optional(),packageManager:z10.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z10.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z10.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z10.object({projectId:z10.uuid(),title:z10.string().trim().min(1).max(240),userReport:z10.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z10.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z10.string().trim().max(1e4).nullable().optional(),outcome:z10.string().trim().max(1e4).nullable().optional(),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z10.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z10.object({fingerprint:z10.string().trim().min(1).max(240),title:z10.string().trim().min(1).max(240),description:z10.string().trim().min(1).max(1e4),affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z10.string().trim().min(1).max(64).nullable().optional(),workaround:z10.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z10.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z10.object({changeReference:z10.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z10.string().trim().min(1).max(1e4),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z10.object({recipientEmail:z10.email().optional(),subject:z10.string().trim().min(1).max(200).default("An update from Fimo"),message:z10.string().trim().min(1).max(5e3),locale:z10.string().trim().min(2).max(20),reason:z10.string().trim().min(1).max(1e3),acknowledgePolicy:z10.literal(!0)}),OpsSentryIssueIdSchema=z10.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z10.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z10.object({projectId:z10.uuid(),from:z10.coerce.date(),to:z10.coerce.date(),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBillingCacheInvalidateInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z10.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z10.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z10.object({kind:z10.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z10.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z10.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z10.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z10.object({migrationId:OpsMigrationIdSchema,projectEnv:z10.string().trim().min(1).max(255).default("main"),reason:z10.string().trim().min(1).max(1e3)}),OpsProjectOperationApplyInputSchema=z10.intersection(OpsProjectOperationPlanInputSchema,z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z11}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z11.object({kind:z11.literal("say"),label:z11.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z11.string().min(1).max(240).optional(),message:z11.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z11.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z11.object({kind:z11.literal("app"),command:z11.literal("publish")}).strict(),BlockBaseSchema=z11.object({fallback:z11.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z11.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z11.literal("choices"),text:z11.string().max(500).optional(),actions:z11.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z11.discriminatedUnion("kind",[z11.object({kind:z11.literal("entry"),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("asset"),assetId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("url"),url:z11.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z11.literal("table"),columns:z11.array(z11.object({label:z11.string().min(1).max(24)})).min(2).max(4),rows:z11.array(z11.object({cells:z11.array(z11.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z11.literal("cards"),layout:z11.enum(["rail","stack"]).optional(),items:z11.array(z11.object({title:z11.string().min(1).max(60),subtitle:z11.string().min(1).max(120).optional(),imageUrl:z11.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z11.literal("entry"),label:z11.string().min(1).max(80),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120),path:z11.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z11.literal("assets"),items:z11.array(z11.object({url:z11.url({protocol:/^https$/}).max(2e3),alt:z11.string().min(1).max(120),label:z11.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z11.literal("callout"),title:z11.string().min(1).max(80),text:z11.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z11.literal("stat"),items:z11.array(z11.object({label:z11.string().min(1).max(24),value:z11.string().min(1).max(16),delta:z11.string().min(1).max(12).optional(),tone:z11.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z11.literal("chart"),unit:z11.string().min(1).max(12).optional(),points:z11.array(z11.object({label:z11.string().min(1).max(12),value:z11.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z11.object({question:z11.string().min(1).max(500),header:z11.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z11.boolean(),recommended:z11.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z11.literal("form"),steps:z11.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z11.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z11.object({header:z11.string().min(1).max(25),question:z11.string().min(1).max(500),answer:z11.string().min(1).max(3e3),selectedLabels:z11.array(z11.string().min(1).max(120)).max(8),freeText:z11.string().max(2e3),skipped:z11.boolean()}),ChatFormAnswerMetadataSchema=z11.object({toolCallId:z11.string().max(255).optional(),shortTitle:z11.string().max(80).optional(),questions:z11.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z11.string().min(1).max(255)})}});import{z as z12}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingRewriteSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z12.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z12.object({dev:z12.string().trim().min(1).optional(),build:z12.string().trim().min(1).optional(),install:z12.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z12.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z12.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingRewriteSchema=z12.object({source:z12.string().min(1),destination:z12.string().min(1)}),FimoHostingConfigSchema=z12.object({rewrites:z12.array(FimoHostingRewriteSchema).optional()}).strict(),FimoAppConfigSchema=z12.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function pageRouteParamNames(path49){return[...path49.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path49){return pageRouteParamNames(path49).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record2=value;return typeof record2.id=="string"?record2.id:Object.fromEntries(Object.entries(record2).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z13}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z13.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z13.string(),displayName:z13.string().nullable(),subdomain:z13.string().nullable().optional(),subdomainUpdatedAt:z13.date().nullable().optional(),organizationId:z13.string().nullable(),createdBy:z13.string().nullable(),previewEnabled:z13.boolean().default(!0),enabledChatModels:z13.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z13.string(),thumbnailUrl:z13.string().nullable(),publishedThumbnailUrl:z13.string().nullable(),category:z13.string().nullable(),appUrl:z13.string().nullable(),lastPublishedAt:z13.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z13.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z13.object({id:z13.uuid(),name:z13.string(),displayName:z13.string().nullable(),thumbnailUrl:z13.string().nullable(),category:z13.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z13.object({id:z13.string(),name:z13.string(),avatar:z13.string().nullable(),color:z13.object({bg:z13.string(),text:z13.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z13.object({path:z13.string(),content:z13.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z13.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z13.object({id:z13.string(),messageId:z13.string(),versionId:z13.string().nullable(),role:ProjectChatMessageRole,parts:z13.array(z13.any()),createdAt:z13.coerce.date()}),MessageUserMetadataSchema=z13.object({id:z13.string(),name:z13.string().nullable().optional(),image:z13.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z13.number(),metadata:z13.object({user:MessageUserMetadataSchema,changeManifest:z13.array(z13.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z13.object({versionId:z13.uuid(),commitHash:z13.string(),name:z13.string(),description:z13.string().nullable(),kind:z13.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z13.object({versionCount:z13.number().int().nonnegative(),snapshotBytes:z13.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z13.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z13.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z13.object({content:z13.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z13.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z13.object({success:z13.boolean(),message:z13.string().optional(),warning:z13.string().optional(),durationMs:z13.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z13.object({isPublished:z13.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z13.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z13.object({success:z13.boolean(),message:z13.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z13.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z14}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,ResolvedBranchEnvironmentDTOSchema,ProjectEnvListItemDTOSchema,ProjectEnvListItemDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectEnvStatusSchema=z14.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z14.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z14.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z14.string().nullable(),deletedAt:z14.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z14.object({id:z14.union([z14.literal(PREVIEW_ENVIRONMENT_KEY),z14.uuid()]),name:z14.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z14.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z14.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z14.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z14.object({surface:z14.enum(["code","schemas","content","translations","assets","forms"]),status:z14.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z14.number().int().nonnegative(),conflictCount:z14.number().int().nonnegative()}),EnvDiffResultSchema=z14.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z14.coerce.date(),surfaces:z14.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z15}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z15.object({projectId:z15.uuid(),name:z15.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z15.literal("production"),sourceBranch:EnvSchema,isPublished:z15.boolean(),url:z15.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PREVIEW_ENVIRONMENT_KEY),kind:z15.literal("preview"),matchedBranchCount:z15.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z15.literal("custom"),matchedBranchCount:z15.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z15.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z15.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z15.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z15.object({deletedId:z15.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z16}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z16.object({kind:z16.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z16.object({kind:z16.enum(["variable","secret"]),value:z16.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z16.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z16.object({kind:z16.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z16.object({id:z16.uuid(),projectId:z16.uuid(),key:z16.string(),kind:z16.literal("secret"),exposure:z16.literal("private"),environment:EnvironmentKeySchema,maskedValue:z16.string().optional(),createdAt:z16.date().transform(value=>value.toISOString()),updatedAt:z16.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z16.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z17}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z17.object({success:z17.literal(!0),downloadUrl:z17.string(),expiresAt:z17.string(),fileSize:z17.number(),duration:z17.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z17.object({success:z17.literal(!0),projectId:z17.string(),projectName:z17.string(),displayName:z17.string(),projectUrl:z17.string(),duration:z17.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z17.object({contentTypes:z17.number(),entries:z17.number(),assets:z17.number(),translations:z17.number(),forms:z17.number(),codeFiles:z17.number(),assetFiles:z17.number()}),ImportPreviewSurfaceDTOSchema=z17.object({name:z17.string(),included:z17.boolean(),count:z17.number().optional(),note:z17.string().optional()}),ImportPreviewDTOSchema=z17.object({projectName:z17.string(),displayName:z17.string().nullable(),category:z17.string().nullable(),exportedAt:z17.string(),version:z17.string(),envScope:z17.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z17.array(ImportPreviewSurfaceDTOSchema),fileSize:z17.number(),fileName:z17.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z17.object({success:z17.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z18}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z18.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z18.object({type:z18.literal("manual")}),ScheduleTriggerSchema=z18.object({type:z18.literal("schedule"),cron:z18.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z18.string().optional()}),WebhookTriggerSchema=z18.object({type:z18.literal("webhook"),path:z18.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z18.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemTriggerStateSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z20.boolean(),wired:z20.boolean(),syncError:z20.string().nullable()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),triggerStates:z20.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z21.object({args:z21.unknown().optional(),requestId:z21.string().min(1).max(128).optional()}),DispatchSkippedSchema=z21.object({skipped:z21.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z21.object({sessionId:z21.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z21.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z23.object({cpuMs:z23.number().nonnegative().default(0),netBytes:z23.number().nonnegative().default(0),walltimeMs:z23.number().nonnegative().default(0),llmTokensIn:z23.number().nonnegative().optional(),llmTokensOut:z23.number().nonnegative().optional(),stepCount:z23.number().int().nonnegative().optional(),toolCallCounts:z23.record(z23.string().min(1).max(120),z23.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),env:EnvSchema,agentName:z23.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z23.unknown().optional(),capabilities:z23.array(z23.string()).optional(),dataSources:z23.array(z23.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z23.string().nullable(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),cancelledAt:z23.coerce.date().nullable(),costUsd:z23.number().nonnegative(),costCeilingUsd:z23.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z23.boolean(),lastCheckpointId:z23.uuid().nullable(),branchEnvId:z23.uuid().nullable(),parentSessionId:z23.uuid().nullable(),terminalReason:z23.string().nullable(),errorMessage:z23.string().nullable(),report:z23.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z23.object({id:z23.uuid(),sessionId:z23.uuid(),checkpointIdx:z23.number().int().nonnegative(),payloadRef:z23.string(),payloadSizeBytes:z23.number().int().nonnegative(),checksum:z23.string().length(64),createdAt:z23.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z23.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z23.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z23.object({session:AgentSessionDTOSchema,checkpoints:z23.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z23.object({reason:z23.string().min(1).max(120).optional()})}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z25.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z25.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z25.enum(["secret_text"]),IntegrationCredentialUsageSchema=z25.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z25.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z25.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z25.object({mode:IntegrationAuthModeSchema,label:z25.string().min(1),description:z25.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z25.object({id:z25.string().min(1),label:z25.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z25.boolean()}),IntegrationToolDefinitionDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),description:z25.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z25.object({title:z25.string().min(1),description:z25.string().min(1),command:z25.string().min(1).optional()}),IntegrationInfoDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z25.array(IntegrationAuthModeDTOSchema),credentials:z25.array(IntegrationCredentialDefinitionDTOSchema),tools:z25.array(IntegrationToolDefinitionDTOSchema),recipes:z25.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),installed:z25.boolean(),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z25.string().nullable(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),connectionStatus:z25.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),installedAt:z25.coerce.date().nullable(),updatedAt:z25.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z25.string(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z25.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z25.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z25.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z25.object({value:z25.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z25.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z25.object({id:z25.uuid(),organizationId:z25.string().min(1),integrationKey:z25.string().min(1),alias:z25.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z25.string().min(1),externalAccountName:z25.string().nullable(),externalBotUserId:z25.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z25.array(z25.string()),connectedAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z25.object({alias:z25.string().min(1).max(120).optional(),token:z25.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z25.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),alias:z25.string().min(1).max(120),token:z25.string().min(1)}),z25.object({mode:z25.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z25.object({integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),integrationKey:z25.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z25.object({mode:z25.literal("oauth"),integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()})]),BindProjectChannelRequestSchema=z25.object({ref:z25.string().min(1),connectionAlias:z25.string().min(1).optional(),agentName:z25.string().min(1).max(160).nullable().optional(),force:z25.boolean().optional()}),ListProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1)}),SearchProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1),connectionAlias:z25.string().min(1),query:z25.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),connectionId:z25.uuid(),externalWorkspaceId:z25.string().min(1),externalChannelId:z25.string().min(1),externalChannelName:z25.string().nullable(),agentName:z25.string().nullable(),enabled:z25.boolean(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z25.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z25.object({id:z25.string().min(1),name:z25.string().min(1),visibility:z25.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z25.string().min(1).nullable(),canMove:z25.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z25.object({markdown:z25.boolean().optional(),summary:z25.boolean().optional(),links:z25.boolean().optional(),images:z25.boolean().optional(),html:z25.union([z25.literal("cleaned"),z25.literal("raw"),z25.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z25.object({url:z25.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z25.object({query:z25.string().min(1),maxResults:z25.number().int().positive().max(20).optional(),sources:z25.array(z25.enum(["web","news","images"])).min(1).max(3).optional(),categories:z25.array(z25.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z25.enum(["hour","day","week","month","year"]).optional(),location:z25.string().min(1).max(160).optional(),country:z25.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z25.object({url:z25.string().url(),search:z25.string().min(1).optional(),limit:z25.number().int().positive().max(200).optional(),includeSubdomains:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z25.object({url:z25.string().url(),limit:z25.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z25.object({text:z25.string().min(1).max(200).optional(),cron:z25.string().min(1).max(120).optional(),timezone:z25.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z25.object({type:z25.enum(["scrape","crawl"]).default("scrape"),urls:z25.array(z25.string().url()).min(1).max(50),scrapeOptions:z25.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z25.object({name:z25.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z25.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z25.string().min(1).max(2e3).optional(),judgeEnabled:z25.boolean().optional(),retentionDays:z25.number().int().min(1).max(365).optional(),notification:z25.object({email:z25.object({enabled:z25.boolean().default(!0),recipients:z25.array(z25.string().email()).min(1).max(20),includeDiffs:z25.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z25.object({monitorId:z25.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z25.string().uuid()}),RunProjectIntegrationToolRequestSchema=z25.object({tool:z25.string().min(1),input:z25.record(z25.string(),z25.unknown()),connectionAlias:z25.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z25.object({provider:z25.string().min(1),providerCredits:z25.number().nonnegative().optional(),providerCostUsd:z25.number().nonnegative().optional(),requests:z25.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z25.object({credits:z25.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()}),FirecrawlSearchToolOutputSchema=z25.object({query:z25.string(),provider:z25.literal("firecrawl"),warning:z25.string().optional(),results:z25.array(z25.object({title:z25.string(),url:z25.string(),snippet:z25.string().optional(),content:z25.string().optional(),score:z25.number().optional(),publishedAt:z25.string().optional()}))}),FirecrawlMapToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),count:z25.number(),links:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),description:z25.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),total:z25.number(),pages:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()})),warning:z25.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z25.object({cron:z25.string().optional(),text:z25.string().optional(),timezone:z25.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z25.object({id:z25.string().optional(),urls:z25.array(z25.string()).optional(),scrapeOptions:z25.record(z25.string(),z25.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z25.object({id:z25.string(),name:z25.string(),status:z25.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z25.string().nullable().optional(),lastRunAt:z25.string().nullable().optional(),currentCheckId:z25.string().nullable().optional(),targets:z25.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z25.string().nullable().optional(),judgeEnabled:z25.boolean().optional(),estimatedCreditsPerMonth:z25.number().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z25.object({id:z25.string(),monitorId:z25.string(),scheduledFor:z25.string().nullable().optional(),startedAt:z25.string().nullable().optional(),finishedAt:z25.string().nullable().optional(),estimatedCredits:z25.number().optional(),reservedCredits:z25.number().optional(),actualCredits:z25.number().optional(),billingStatus:z25.string().nullable().optional(),summary:z25.object({totalPages:z25.number().optional(),same:z25.number().optional(),changed:z25.number().optional(),new:z25.number().optional(),removed:z25.number().optional(),error:z25.number().optional()}).passthrough().optional(),error:z25.string().nullable().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitors:z25.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),deleted:z25.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),checks:z25.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),check:FirecrawlMonitorCheckOutputSchema,next:z25.string().optional()}),FirecrawlToolKeySchema=z25.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z25.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),tool:z25.string().min(1),connectionAlias:z25.string().min(1).nullable().optional(),output:z25.record(z25.string(),z25.unknown()),executedAt:z25.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z25.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z25.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z25.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z25.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z25.array(ProjectChannelCandidateDTOSchema))}});import{z as z26}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z26.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z26.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z26.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z26.object({userId:z26.string().min(1),name:z26.string(),email:z26.string().min(1),subscribed:z26.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z26.object({maxSubscribers:z26.number().int().positive(),subscriberCount:z26.number().int().nonnegative(),effectiveRecipientCount:z26.number().int().nonnegative(),currentUserSubscribed:z26.boolean(),candidates:z26.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z26.object({userIds:z26.array(z26.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z26.object({topic:UserManagedNotificationTopicSchema,enabled:z26.boolean(),source:z26.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z26.object({topics:z26.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z26.object({enabled:z26.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z26.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z26.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z26.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z26.string().nullable(),maskedEmail:z26.string().min(1),applied:z26.boolean(),expiresAt:z26.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z26.object({scheduleId:z26.string().min(1),scheduleName:z26.string(),projectId:z26.string().min(1),projectName:z26.string(),env:z26.string().min(1)}),FollowedSchedulesSchema=z26.object({schedules:z26.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z27}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z27.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z27.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z27.uuid(),env:z27.string().min(1),name:z27.string().min(1),cron:z27.string().min(1),command:z27.string().min(1),secretKeys:z27.array(z27.string().min(1)),enabled:z27.boolean(),lastRunAt:z27.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z27.string().nullable(),overPolicyReasons:z27.array(z27.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120),cron:z27.string().min(1).max(120),command:z27.string().min(1).max(500),secretKeys:z27.array(ProjectSecretKeySchema).default([]),enabled:z27.boolean().optional()}),UpdateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120).optional(),cron:z27.string().min(1).max(120).optional(),command:z27.string().min(1).max(500).optional(),secretKeys:z27.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z27.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z27.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z27.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z27.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z27.object({maxRuns:z27.number().int().positive(),retentionDays:z27.number().int().positive().nullable(),outputRetentionDays:z27.number().int().positive(),maxOutputBytes:z27.number().int().positive()}),SchedulePolicyStateSchema=z27.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z27.object({code:z27.enum(["Free","Premium"]),source:z27.enum(["cached_subscription","free_fallback"]),activeSchedules:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),concurrency:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),compute:z27.object({settledMs:z27.number().int().nonnegative(),reservedMs:z27.number().int().nonnegative(),includedMs:z27.number().int().positive(),remainingMs:z27.number().int().nonnegative(),resetsAt:z27.coerce.date()}),upgrade:z27.object({code:z27.literal("Premium"),activeSchedulesLimit:z27.number().int().positive(),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),maxConcurrentRuns:z27.number().int().positive(),computeIncludedMs:z27.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z27.array(z27.string())}),ProjectScheduleUsageSchema=z27.object({runCount:z27.number().int().nonnegative(),runsWithOutput:z27.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z27.object({id:z27.uuid(),scheduleId:z27.uuid(),projectId:z27.uuid(),env:z27.string().min(1),scheduleName:z27.string().min(1),command:z27.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z27.object({id:z27.string().min(1),name:z27.string().min(1)}).nullable(),queuedAt:z27.coerce.date(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),exitCode:z27.number().int().nullable(),errorCode:z27.string().nullable(),error:z27.string().nullable(),outputBytes:z27.number().int().nonnegative(),outputTruncated:z27.boolean(),outputExpiresAt:z27.coerce.date().nullable(),metadataExpiresAt:z27.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z27.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z27.coerce.date().nullable(),items:z27.array(z27.object({key:z27.string().min(1),updatedAt:z27.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z27.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z27.object({trigger:z27.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z27.object({limit:z27.coerce.number().int().min(1).max(100).default(25),cursor:z27.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z27.object({items:z27.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z27.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z27.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z27.object({items:z27.array(ProjectScheduleRunDTOSchema),nextCursor:z27.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z28}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z28.object({id:z28.uuid(),occurredAt:z28.coerce.date(),projectId:z28.uuid().nullable(),env:z28.string().nullable(),actor:z28.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z28.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z28.unknown().optional(),ipAddress:z28.string().nullable().optional(),userAgent:z28.string().nullable().optional(),error:z28.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z28.object({rows:z28.array(AuditLogRowDTOSchema),nextCursor:z28.string().nullable()})),AuditLogQuerySchema=z28.object({env:z28.string().optional(),action:AuditActionSchema.optional(),actor:z28.string().optional(),from:z28.coerce.date().optional(),to:z28.coerce.date().optional(),limit:z28.coerce.number().int().min(1).max(200).optional(),cursor:z28.string().optional()})}});import{z as z29}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z29.object({surface:SurfaceNameSchema,key:z29.string(),label:z29.string()}),InlineSchema=z29.object({text:z29.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z29.discriminatedUnion("type",[z29.object({type:z29.literal("paragraph"),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("preview"),ref:DiffRefSchema,caption:z29.string().optional()}),z29.object({type:z29.literal("code"),code:z29.string(),lang:z29.string().optional(),caption:z29.string().optional()}),z29.object({type:z29.literal("risk"),level:z29.enum(["warning","error"]),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("list"),items:z29.array(z29.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z29.object({headline:z29.string(),blocks:z29.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z29.object({summary:EnvDiffSummarySchema,fingerprint:z29.string(),generatedAt:z29.coerce.date(),cached:z29.boolean().optional(),credits:z29.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z30}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z30.object({date:z30.string(),visitors:z30.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z30.object({key:z30.string(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z30.object({path:z30.string(),pageName:z30.string().nullable().optional(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z30.object({preset:z30.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z30.string(),requestedTo:z30.string(),effectiveFrom:z30.string(),effectiveTo:z30.string(),isRetentionLimited:z30.boolean(),groupBy:z30.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z30.object({date:z30.string(),content:z30.string(),updatedAt:z30.string(),updatedByUserId:z30.string()}),ProjectPageviewAnalyticsDTOSchema=z30.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative(),bounceRate:z30.number().min(0).max(100),viewsPerVisit:z30.number().nonnegative(),averageVisitDurationSeconds:z30.number().nonnegative(),visitorsSeries:z30.array(ProjectDailyVisitorsDTOSchema),topPages:z30.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z30.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z31}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z31.object({id:z31.string(),email:z31.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z31.coerce.date(),createdAt:z31.coerce.date(),inviterUserId:z31.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z31.object({id:z31.string(),token:z31.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z31.object({success:z31.boolean(),projectId:z31.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z32}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z32.object({id:z32.string(),name:z32.string(),image:z32.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z32.object({count:z32.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z32.object({counts:z32.object({signed_up:z32.int(),activated:z32.int()}),credits:z32.object({total:z32.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z32.email(),emailVerified:z32.boolean(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z33}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z33.object({id:z33.string(),principalType:ProjectPrincipalTypeSchema,principalId:z33.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z33.coerce.date(),expiresAt:z33.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z33.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z33.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z33.record(z33.string(),z33.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z33.object({access:z33.array(ProjectAccessItemDTOSchema),invites:z33.array(ProjectInviteDTOSchema),organization:z33.object({name:z33.string().nullable(),logo:z33.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z33.object({success:z33.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z33.object({success:z33.boolean(),projectId:z33.uuid()}))}});import{z as z34}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z34.object({publicationStatus:PublicationStatusSchema,appUrl:z34.string().nullable(),lastPublishedAt:z34.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z35}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z35.object({url:z35.url(),expiresAt:z35.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z36}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z36.string(),slug:z36.string().nullable(),logo:z36.string().nullable(),metadata:z36.record(z36.string(),z36.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z36.object({id:z36.string(),name:z36.string(),email:z36.email(),image:z36.string().nullable()}),OrganizationMemberDTOSchema=z36.object({id:z36.string(),userId:z36.string(),organizationId:z36.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z36.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z37}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z37.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z37.object({reason:CancellationReasonCodeSchema,details:z37.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z37.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z37.object({included:z37.number().optional(),unitPrice:z37.number().optional(),dailyCap:z37.number().nullable().optional()}),EntitlementsDTOSchema=z37.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z37.object({retentionDays:z37.number().int().positive(),canUseExtendedDateRanges:z37.boolean()}).optional(),history:z37.object({retentionDays:z37.number().int().positive()}).optional(),members:z37.object({canInvite:z37.boolean(),maxMembers:z37.number().int().positive().nullable()}).optional(),domains:z37.object({canUseCustomDomains:z37.boolean(),maxDomains:z37.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z37.object({id:z37.string(),external_id:z37.string(),customerId:z37.string(),planId:z37.string(),planCode:TemplateCodeSchema,currentPeriod:z37.object({start:z37.string(),end:z37.string().nullable()}),cancelAt:z37.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z37.string(),nextPaymentAt:z37.string().nullable(),baseAmount:z37.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z37.object({totalCap:z37.number(),dailyCap:z37.number(),usedTotal:z37.number()}),CreditBalanceDTOSchema=z37.object({total:z37.number(),base:z37.number(),dailyBase:z37.number(),purchases:z37.number(),awards:z37.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z37.object({total:z37.number(),nearLimit:z37.boolean(),canChat:z37.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z37.object({dailyFreeAvailable:z37.number(),monthlyAvailable:z37.number(),purchasedAvailable:z37.number(),awardedAvailable:z37.number()}),ProjectDailyCreditAllowanceDTOSchema=z37.object({periodCap:z37.number(),dailyGrant:z37.number(),usedThisPeriod:z37.number(),remainingThisPeriod:z37.number()}),ProjectCreditBalanceDTOSchema=z37.object({projectId:z37.uuid(),organizationId:z37.string(),balance:z37.object({totalAvailable:z37.number(),nearLimit:z37.boolean(),canUseAi:z37.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z37.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().nonnegative(),refillAmountUsd:z37.number().nonnegative()}),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().nonnegative().nullable(),refillAmountUsd:z37.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().min(.01).multipleOf(.01),refillAmountUsd:z37.number().min(.01).multipleOf(.01)}).strict(),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z37.object({invoiceId:z37.string(),newBalance:z37.int(),creditCount:z37.int(),amountUsd:z37.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z37.object({url:z37.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z38}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z38.object({brand:z38.string(),last4:z38.string(),exp:z38.string(),isDefault:z38.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z39}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z39.string().superRefine((path49,ctx)=>{let segments=path49.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z39.object({type:z39.literal("renameField"),contentType:z39.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z39.object({enabled:z39.boolean()}).strict(),ContentTypeDTOSchema=z39.object({id:z39.string(),name:z39.string(),label:z39.string(),isSingleton:z39.boolean(),i18n:ContentTypeI18nSchema,fields:z39.record(z39.string(),FieldDefinitionSchema),createdAt:z39.string(),updatedAt:z39.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z39.object({contentTypes:z39.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z39.object({id:z39.string(),entryId:z39.string(),documentId:z39.string(),slug:z39.string(),locale:z39.string().optional(),createdAt:z39.string(),updatedAt:z39.string(),__fimo:z39.object({contentType:z39.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({limit:z39.number(),offset:z39.number(),total:z39.number(),hasMore:z39.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z39.object({contentType:z39.string(),count:z39.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z39.object({counts:z39.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z39.object({count:z39.number().int().nonnegative(),sourceLocale:z39.string(),targetLocale:z39.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z39.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z39.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z39.union([z39.string(),z39.number(),z39.boolean(),z39.null()]),entryWhereOperatorSchema=z39.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z39.array(entryWhereScalarSchema).optional(),$nin:z39.array(entryWhereScalarSchema).optional(),$contains:z39.string().optional(),$startsWith:z39.string().optional(),$null:z39.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z39.object({data:z39.record(z39.string(),z39.unknown()),locale:z39.string().min(1).optional(),documentId:z39.uuid().optional()}),entryIdsSchema=z39.array(z39.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z39.object({sql:z39.string().min(1)}),BulkCreateEntriesRequestSchema=z39.object({entries:z39.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z39.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z39.object({updates:z39.array(z39.object({id:z39.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,locale:z39.string().min(1).optional()}),z39.object({where:EntryWhereSchema,locale:z39.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z39.object({data:z39.array(z39.record(z39.string(),z39.unknown())),meta:z39.object({rowCount:z39.number().int().nonnegative(),truncated:z39.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({created:z39.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({updated:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({deleted:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z40}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z40.object({index:z40.number().int().nonnegative(),contentType:z40.string(),field:z40.string(),value:z40.string(),against:z40.enum(["stored","batch"]),ownerDocumentId:z40.uuid().optional(),ownerIndex:z40.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z40.object({code:z40.literal("unique_conflict"),message:z40.string(),conflicts:z40.array(UniqueConflictSchema),truncated:z40.boolean().optional()})}});import{z as z41}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z41.object({kind:z41.literal("unique_conflict"),contentType:z41.string(),field:z41.string(),value:z41.string(),documentCount:z41.number().int().positive(),documentIds:z41.array(z41.uuid()),documentIdsTruncated:z41.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z41.object({code:z41.literal("schema_transition_rejected"),message:z41.string(),issues:z41.array(SchemaTransitionIssueSchema),truncated:z41.boolean().optional()})}});import{z as z42}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z42.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z42.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z42.object({field:CmsFieldNameSchema,direction:z42.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z42.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z42.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z42.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z42.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z42.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z43}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z43.object({id:z43.string(),name:z43.string()}),AssetDTOSchema=z43.object({id:z43.string(),name:z43.string(),type:AssetTypeSchema,originalFileName:z43.string().nullable(),parentId:z43.string().nullable(),mimeType:z43.string().nullable(),fileSize:z43.number().nullable(),url:z43.string().nullable(),storageKey:z43.string().nullable(),createdAt:z43.string(),updatedAt:z43.string(),altText:z43.string().nullable().optional(),caption:z43.string().nullable().optional(),aiCaption:z43.string().nullable().optional(),aiAltText:z43.string().nullable().optional(),aiTags:z43.array(z43.string()).nullable().optional(),aiPrimaryColor:z43.string().nullable().optional(),aiProcessingStatus:z43.string().nullable().optional(),width:z43.number().nullable().optional(),height:z43.number().nullable().optional(),path:z43.array(AssetPathItemSchema).optional(),hasChildren:z43.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z43.lazy(()=>z43.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z43.array(AssetDTOSchema))}});import{z as z44}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z44.object({key:z44.string(),value:z44.string().optional(),defaultValue:z44.string(),locale:z44.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z45}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z45.object({id:z45.string(),name:z45.string(),type:z45.enum(["file","folder"]),path:z45.string(),children:z45.lazy(()=>z45.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z45.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z45.object({path:z45.string(),exists:z45.boolean(),type:z45.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z46}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z46.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z46.object({items:z46.array(ProjectMessagePublicDTOSchema),nextCursor:z46.string().nullable()}),ChatLiveTurnDTOSchema=z46.object({invocationId:z46.string(),step:z46.enum(["preparing","working","compacting","merging"]),startedAt:z46.string()}),ChatLiveTurnStateDTOSchema=z46.object({threadId:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z46.object({id:z46.string(),role:z46.enum(["user","assistant"]),parts:z46.array(z46.unknown()),metadata:z46.record(z46.string(),z46.unknown()).nullable(),versionId:z46.string().nullable().optional(),createdAt:z46.date().transform(value=>value.toISOString()),providerMessageId:z46.string().nullable().optional(),invocationId:z46.string().nullable().optional(),invocationStatus:z46.string().nullable().optional(),invocationTerminalReason:z46.string().nullable().optional()}),ChatAttentionDTOSchema=z46.object({type:z46.literal("merge_conflict"),merge:z46.object({mergeId:z46.string().uuid(),projectId:z46.string(),fromEnv:z46.string(),toEnv:z46.string()}),publishAfterMerge:z46.boolean()}),ChatThreadMessagesPageDTOSchema=z46.object({threadId:z46.string().nullable(),title:z46.string().nullable(),messages:z46.array(ChatThreadMessageDTOSchema),nextCursor:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z46.object({kind:z46.literal("replay"),threadId:z46.string(),userMessageId:z46.string()}),ChatQueuedOutcomeDTOSchema=z46.object({kind:z46.literal("queued"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string()}),ChatBusyOutcomeDTOSchema=z46.object({kind:z46.literal("busy"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string().optional()}),ChatRefusedOutcomeDTOSchema=z46.object({kind:z46.literal("refused"),threadId:z46.string(),userMessageId:z46.string(),refusedInvocationId:z46.string(),terminalReason:z46.string()}),ChatNonStreamingOutcomeDTOSchema=z46.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z46.object({success:z46.boolean(),deletedCount:z46.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z46.object({code:z46.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z46.string()})}});import{z as z47}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z47.object({url:z47.string().url(),key:z47.string(),size:z47.number(),contentType:z47.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z48}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z48.object({canAccess:z48.boolean(),permissions:z48.record(z48.string(),z48.boolean()),role:z48.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z49}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z49.string().trim().default(""),sort:z49.enum(["recent","name","relevance"]).default("recent"),category:z49.string().optional()})}});import{z as z50}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z50.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z50.enum(["fimo","external"]),PaymentStatusSchema=z50.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z50.object({id:z50.string().uuid(),domain:z50.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z50.boolean(),price:z50.number().int().nullable(),renewalPrice:z50.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z50.string().nullable(),failureReason:z50.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z50.object({domain:z50.string(),available:z50.boolean(),premium:z50.boolean(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),purchaseType:z50.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z50.object({domain:z50.string(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),premium:z50.boolean(),allowedYears:z50.array(z50.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z50.object({firstName:z50.string().max(100),lastName:z50.string().max(100),companyName:z50.string().max(100).optional(),address1:z50.string().max(255),address2:z50.string().max(255).optional(),city:z50.string().max(100),state:z50.string().max(100),zip:z50.string().max(20),country:z50.string().max(2),phone:z50.string().max(30),email:z50.union([z50.string().email().max(255),z50.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z50.object({firstName:z50.string().min(1).max(100),lastName:z50.string().min(1).max(100),companyName:z50.string().max(100).optional(),address1:z50.string().min(1).max(255),address2:z50.string().max(255).optional(),city:z50.string().min(1).max(100),state:z50.string().min(1).max(100),zip:z50.string().min(1).max(20),country:z50.string().min(1).max(2),phone:z50.string().min(1).max(30),email:z50.string().email().max(255)}),SearchDomainsRequestSchema=z50.object({keyword:z50.string().min(1).max(100),tldFilter:z50.array(z50.string()).optional()}),CheckAvailabilityRequestSchema=z50.object({domains:z50.array(z50.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z50.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z50.object({domain:DomainNameSchema,years:z50.number().int().min(1).max(10).optional().default(3),autoRenew:z50.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z50.object({autoRenew:z50.boolean().optional()}),RenewDomainRequestSchema=z50.object({years:z50.number().int().min(1).max(10).optional().default(1),autoRenew:z50.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z50.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z50.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z50.object({verified:z50.boolean(),email:z50.string().nullable(),verifyBy:z50.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z51}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z51.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z51.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z51.object({txtName:z51.string().nullable().optional(),txtValue:z51.string().nullable().optional(),httpUrl:z51.string().nullable().optional(),httpBody:z51.string().nullable().optional(),cname:z51.string().nullable().optional(),cnameTarget:z51.string().nullable().optional()}),SSLValidationErrorSchema=z51.object({message:z51.string()}),OwnershipVerificationSchema=z51.object({type:z51.string(),name:z51.string(),value:z51.string()}),ProjectDomainSSLDTOSchema=z51.object({status:z51.string(),method:z51.string().nullable(),type:z51.string().nullable(),validationRecords:z51.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z51.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z51.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z51.enum(["subdomain","apex"]),RedirectConfigSchema=z51.object({type:z51.literal("apex_to_www"),linkedDomainId:z51.string()}).nullable().optional(),ProjectDomainDTOSchema=z51.object({id:z51.string(),hostname:z51.string(),status:z51.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z51.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z51.string(),scdCnameTarget:z51.string().optional(),apexTargets:z51.array(z51.string()),dnsAutoConfigured:z51.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z51.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z51.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z51.object({hostname:z51.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z51.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z51.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z51.object({available:z51.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z51.object({success:z51.boolean(),hostname:z51.string()}))}});import{z as z52}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z52.object({available:z52.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z52.object({slug:z52.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z52.object({subdomain:z52.string(),subdomainUpdatedAt:z52.coerce.date()})),SubdomainSuggestionsQuerySchema=z52.object({base:z52.string().max(100).optional(),max:z52.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z52.object({suggestions:z52.array(z52.string())}))}});import{z as z53}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z53.object({translated:z53.number().int().nonnegative(),total:z53.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z53.object({locale:z53.string(),isDefault:z53.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z53.object({defaultLocale:z53.string(),locales:z53.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z53.object({locale:z53.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z53.object({locale:z53.string().min(1).max(40)}),ProjectLocaleMutationSchema=z53.object({locale:z53.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z53.object({locale:z53.string(),entriesDeleted:z53.number().int().nonnegative(),labelsDeleted:z53.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z54}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z54.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z54.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z54.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z54.number(),credits:z54.number().optional(),billingMode:z54.enum(["fimo-credits","provider-account"]).optional(),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z55}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z55.object({options:z55.record(z55.string(),z55.unknown()),name:z55.string().optional(),parentId:z55.string().nullable().optional(),altText:z55.string().optional(),caption:z55.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z55.string().min(1).optional(),model:z55.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z55.object({jobId:z55.string(),status:z55.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z55.string().nullable().optional(),credits:z55.number().optional(),costUsd:z55.number().optional(),billingMode:z55.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z55.object({error:z55.string(),code:z55.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z55.array(GenerationTaskIdSchema).optional(),availableModels:z55.array(z55.string()).optional(),issues:z55.array(z55.unknown()).optional()})}});import{z as z56}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z56.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z56.object({name:z56.string(),key:z56.string(),description:z56.string(),type:FlagTypeSchema,required:z56.boolean(),defaultValue:z56.unknown().optional(),enumValues:z56.array(z56.string()).optional(),isArray:z56.boolean()}),AssetModelPriceSchema=z56.object({unitPrice:z56.number(),unit:z56.string(),confidence:z56.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z56.object({id:z56.string(),shortName:z56.string(),provider:z56.string(),source:z56.string(),modality:z56.enum(["image","video","audio"]),tags:z56.array(z56.string()),displayName:z56.string(),description:z56.string(),flags:z56.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z56.object({model:z56.string(),costUsd:z56.number(),credits:z56.number(),billingMode:z56.enum(["fimo-credits","provider-account"]),confidence:z56.enum(["exact","estimated","metered"]),basis:z56.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z57}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z57.object({tourId:z57.string(),version:z57.string(),status:z57.string(),completedAt:z57.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z57.array(UserTourDTOSchema))}});import{z as z58}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z58.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z58.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z58.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z58.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z58.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z58.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z58.enum(["user","agent","system"]),SupportReportTagSchema=z58.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z58.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z58.object({organization:z58.object({id:z58.string().trim().min(1).max(255),name:z58.string().trim().max(240).optional()}),project:z58.object({id:z58.uuid(),name:z58.string().trim().max(240).optional(),createdAt:z58.coerce.date().optional()}).optional(),environment:z58.string().trim().max(255).optional(),clientVersion:z58.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z58.string().trim().max(200).optional(),limit:z58.coerce.number().int().min(1).max(100).default(50),offset:z58.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z58.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z58.uuid().nullable().optional(),note:z58.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z58.object({kind:SupportReportLinkKindSchema,label:z58.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z58.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z58.object({kind:SupportReportActorKindSchema,id:z58.string().nullable(),name:z58.string().nullable()}),SupportReportLinkDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportLinkKindSchema,label:z58.string(),url:SupportReportHttpUrlSchema,externalId:z58.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportEventKindSchema,body:z58.string().nullable(),metadata:z58.record(z58.string(),z58.unknown()),actor:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z58.object({id:z58.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z58.array(z58.string()),source:SupportReportSourceSchema,message:z58.string(),reporter:z58.object({id:z58.string().nullable(),name:z58.string().nullable(),email:z58.string().nullable()}),organization:z58.object({id:z58.string().nullable(),name:z58.string()}),project:z58.object({id:z58.uuid().nullable(),name:z58.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z58.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z58.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}).nullable(),duplicateOfReportId:z58.uuid().nullable(),resolvedAt:z58.coerce.date().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z58.string().nullable(),clientVersion:z58.string().nullable(),links:z58.array(SupportReportLinkDTOSchema),events:z58.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z58.object({reports:z58.array(SupportReportSummaryDTOSchema),total:z58.number().int().nonnegative(),statusCounts:z58.object({new:z58.number().int().nonnegative(),in_progress:z58.number().int().nonnegative(),waiting:z58.number().int().nonnegative(),resolved:z58.number().int().nonnegative(),duplicate:z58.number().int().nonnegative(),irrelevant:z58.number().int().nonnegative(),ignored:z58.number().int().nonnegative()}),limit:z58.number().int().positive(),offset:z58.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z58.object({id:z58.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z58.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z59}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z59.iso.datetime({offset:!0}).pipe(z59.coerce.date()),OpsRecentChatInputSchema=z59.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z59.string().trim().min(1).max(255).optional(),limit:z59.coerce.number().int().min(1).max(200).default(100),cursor:z59.string().trim().min(1).max(2e3).optional(),slim:z59.boolean().default(!0),reason:z59.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z59.object({id:z59.string(),threadId:z59.string(),providerMessageId:z59.string().nullable(),invocationId:z59.string().nullable(),env:z59.string().nullable(),role:z59.string(),parts:z59.array(z59.record(z59.string(),z59.unknown())),metadata:z59.object({status:z59.string().optional(),traceUrl:z59.string().optional(),externalFileChanges:z59.array(z59.unknown()).optional()}),stats:z59.object({toolCount:z59.number().int().nonnegative(),failedToolCount:z59.number().int().nonnegative()}),createdAt:z59.iso.datetime({offset:!0}),project:z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),organizationId:z59.string().nullable()})}),OpsRecentChatResponseSchema=z59.object({target:z59.object({backendProfile:OpsBackendProfileSchema,projectEnv:z59.string().nullable()}),window:z59.object({from:z59.iso.datetime({offset:!0}),to:z59.iso.datetime({offset:!0})}),messages:z59.object({items:z59.array(OpsRecentChatMessageSchema),nextCursor:z59.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z60}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z60.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z60.literal(!1),reason:z60.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z61}from"zod";function createAgentRunWebhookEventDataSchema(status){return z61.object({run:z61.object({id:z61.string(),agentName:z61.string(),trigger:z61.string(),status:z61.literal(status),startedAt:z61.string().nullable(),finishedAt:z61.string().nullable(),reason:z61.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z61.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z61.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z61.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z61.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z61.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z61.union([z61.literal(0),z61.literal(5),z61.literal(30),z61.literal(60)]),EntryChangedWebhookEventDataSchema=z61.object({reason:WebhookEntryChangeReasonSchema,operationId:z61.string().optional(),batch:z61.object({index:z61.number().int().positive(),total:z61.number().int().positive()}).optional(),changes:z61.array(z61.object({action:WebhookEntryChangeActionSchema,contentType:z61.string(),id:z61.string(),documentId:z61.string(),locale:z61.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z61.object({form:z61.object({id:z61.string(),label:z61.string()}),submission:z61.object({id:z61.string(),data:z61.record(z61.string(),z61.unknown()),submittedAt:z61.string()})}),PublishStartedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("publishing"),startedAt:z61.string()})}),PublishSucceededWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("published"),url:z61.string(),publishedAt:z61.string(),firstPublish:z61.boolean()})}),PublishFailedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("failed"),reason:z61.string()})}),PublishUnpublishedWebhookEventDataSchema=z61.object({publication:z61.object({previousUrl:z61.string(),unpublishedAt:z61.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),classification:z61.string(),summary:z61.string(),reasons:z61.array(z61.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),resolution:z61.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z61.object({report:z61.object({weekStart:z61.string(),weekEnd:z61.string(),pageviews:z61.number(),visitors:z61.number(),previousPageviews:z61.number(),previousVisitors:z61.number()})}),MediaAssetWebhookEventDataSchema=z61.object({id:z61.string().nullable(),name:z61.string().nullable(),type:z61.string(),mimeType:z61.string().nullable(),fileSize:z61.number().nullable()}),MediaUploadedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["updated","moved","analysis"]),analysis:z61.object({category:z61.string(),status:z61.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("generated"),generation:z61.object({model:z61.string(),mode:z61.string()})}),MediaProcessingFailedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["analysis","generation"]),failure:z61.object({code:z61.string()})}),DomainCreatedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string()})}),LabelChangedWebhookEventDataSchema=z61.object({changes:z61.array(z61.object({action:z61.enum(["created","updated","deleted"]),key:z61.string(),locale:z61.string(),value:z61.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),isDefault:z61.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),previousCode:z61.string()})}),LocaleDeletedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),entriesDeleted:z61.number().int().nonnegative(),labelsDeleted:z61.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z61.object({merge:z61.object({id:z61.string(),from:EnvSchema,to:EnvSchema,applied:z61.array(z61.object({surface:SurfaceNameSchema,count:z61.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema}),version:z61.object({versionId:z61.uuid(),name:z61.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z61.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z61.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z61.discriminatedUnion("source",[z61.object({source:z61.literal("literal"),value:z61.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z61.object({source:z61.literal("secret"),key:z61.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z61.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z61.object({name:z61.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z61.object({name:z61.string(),source:z61.enum(["literal","secret"]),secretKey:z61.string().nullable(),secretPrefix:z61.string().nullable(),configured:z61.literal(!0)}),WebhookFilterSchema=z61.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z61.string().min(1).max(255).optional(),agentName:z61.string().min(1).max(120).optional(),mediaType:z61.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z61.string().min(1).max(255).optional(),locale:z61.string().min(1).max(120).optional()}),JsonValueSchema=z61.lazy(()=>z61.union([z61.string(),z61.number(),z61.boolean(),z61.null(),z61.array(JsonValueSchema),z61.record(z61.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z61.url(),enabled:z61.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z61.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z61.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z61.url().optional(),enabled:z61.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z61.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z61.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z61.object({eventType:WebhookEventTypeSchema.optional(),data:z61.record(z61.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z61.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z61.uuid(),name:z61.string(),eventType:WebhookEventTypeSchema,enabled:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z61.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z61.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z61.coerce.date().nullable(),deliveryStats24h:z61.object({succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z61.uuid(),projectId:z61.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z61.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z61.number().int().positive(),test:z61.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z61.number().int().nonnegative(),responseStatus:z61.number().int().nullable(),lastErrorCode:z61.string().nullable(),lastErrorMessage:z61.string().nullable(),payloadAvailable:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z61.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z61.string().nullable(),qstashMessageId:z61.string().nullable(),deliveredAt:z61.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z61.object({items:z61.array(WebhookDeliveryDTOSchema),pagination:z61.object({page:z61.number().int().positive(),limit:z61.number().int().positive(),total:z61.number().int().nonnegative(),totalPages:z61.number().int().positive(),hasMore:z61.boolean()}),stats:z61.object({total:z61.number().int().nonnegative(),succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z61.object({id:z61.uuid(),deliveryId:z61.uuid(),attempt:z61.number().int().positive(),status:z61.enum(["delivering","succeeded","failed"]),responseStatus:z61.number().int().nullable(),durationMs:z61.number().int().nonnegative(),responseExcerpt:z61.string().nullable(),errorCode:z61.string().nullable(),errorMessage:z61.string().nullable(),createdAt:z61.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z61.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z61.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z62}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z62.object({key:z62.literal("fimo-2"),enabled:z62.boolean(),dismissed:z62.boolean().default(!1),interacted:z62.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z63}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z63.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z63.object({total:z63.number(),base:z63.number(),purchases:z63.number(),awards:z63.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z63.object({id:z63.string(),name:z63.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z63.object({type:z63.string(),brand:z63.string().nullable(),last4:z63.string().nullable(),expirationDate:z63.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z63.object({currency:z63.string(),nextPaymentAmount:z63.number().nullable(),nextPaymentAt:z63.string().nullable(),billingInterval:z63.string().nullable(),totalAmount:z63.number().nullable(),discountAmount:z63.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z63.object({id:z63.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z63.string().nullable(),currentPeriodEndsAt:z63.string().nullable(),renewsAt:z63.string().nullable(),cancelAt:z63.string().nullable(),renewAutomatically:z63.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z63.object({type:z63.enum(["low_balance","critical_balance","approaching_limit"]),message:z63.string(),estimatedPromptsRemaining:z63.number().nullable(),avgCostPerPrompt:z63.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z63.object({monthlyCredits:z63.number().nullable(),usedThisPeriod:z63.number(),remainingThisPeriod:z63.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z63.object({organizationId:z63.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z63.string().nullable(),tenureDays:z63.number().int().nonnegative(),capturedAt:z63.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z63.object({hasSubscription:z63.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z63.number().nullable(),alerts:z63.array(CreditAlertDTOSchema),portalUrl:z63.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z63.object({creditCount:z63.number().int().positive(),expiresAt:z63.string().datetime().nullable().optional(),message:z63.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("free"),amountCents:z63.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("purchase"),amountCents:z63.number().int().positive()}),CreditTopupRequestDTOSchema=z63.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z63.object({success:z63.boolean(),transactionId:z63.string().nullable(),newBalance:z63.number(),creditCount:z63.number(),type:z63.enum(["free","purchase"]),invoiceId:z63.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z64}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z64.object({totalCredits:z64.number(),totalCostUsd:z64.number(),totalMessages:z64.number(),avgCostPerMessage:z64.number(),periodStart:z64.string().nullable(),periodEnd:z64.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z64.object({date:z64.string(),credits:z64.number(),costUsd:z64.number(),messages:z64.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z64.array(UsageByUserForProjectDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z64.object({summary:UsageSummaryDTOSchema,byProject:z64.array(UsageByProjectDTOSchema),byUser:z64.array(UsageByUserDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z65}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z65.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z65.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z65.object({startDate:z65.string().optional(),endDate:z65.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z65.coerce.number().int().positive().default(1),limit:z65.coerce.number().int().positive().max(100).default(20),sortBy:z65.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z65.string().optional(),activeOnly:z65.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z65.object({totalCredits:z65.number(),totalCostUsd:z65.number(),totalMessages:z65.number(),avgCostPerMessage:z65.number(),avgCreditsPerMessage:z65.number(),periodStart:z65.string(),periodEnd:z65.string(),creditsChange:z65.number().nullable(),costChange:z65.number().nullable(),messagesChange:z65.number().nullable(),unattributedCredits:z65.number(),unattributedCostUsd:z65.number(),unattributedMessages:z65.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z65.object({date:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z65.object({organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number(),projectCount:z65.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z65.object({userId:z65.string(),userName:z65.string().nullable(),userEmail:z65.string().nullable(),userImage:z65.string().nullable(),organizationId:z65.string().nullable(),organizationName:z65.string().nullable(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),projectCount:z65.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z65.object({projectId:z65.string(),projectName:z65.string(),projectDisplayName:z65.string().nullable(),organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z65.object({id:z65.string(),name:z65.string(),value:z65.number(),percentage:z65.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z65.object({day:z65.number(),hour:z65.number(),value:z65.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z65.object({summary:UsageOverviewSummaryDTOSchema,timeline:z65.array(UsageTimelinePointDTOSchema),topOrganizations:z65.array(OrganizationUsageRowDTOSchema),topUsers:z65.array(UserUsageRowDTOSchema),topProjects:z65.array(ProjectUsageRowDTOSchema),creditDistribution:z65.array(UsageDistributionItemDTOSchema),userDistribution:z65.array(UsageDistributionItemDTOSchema),heatmap:z65.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z65.object({page:z65.number(),limit:z65.number(),totalItems:z65.number(),totalPages:z65.number(),hasMore:z65.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z65.object({organizations:z65.array(OrganizationUsageRowDTOSchema),top:z65.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z65.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z65.object({users:z65.array(ExtendedUserUsageRowDTOSchema),top:z65.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z65.object({projects:z65.array(ExtendedProjectUsageRowDTOSchema),top:z65.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z65.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z65.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z65.object({credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),createdAt:z65.string(),memberCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z65.object({id:z65.string(),name:z65.string().nullable(),email:z65.string(),image:z65.string().nullable(),createdAt:z65.string(),organizationCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),createdAt:z65.string(),organizationId:z65.string(),organizationName:z65.string(),ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z66}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z66.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z66.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z66.object({command:z66.string().min(1).max(1e4),cwd:z66.string().optional(),projectEnv:EnvSchema.optional(),env:z66.record(z66.string(),z66.string()).optional(),name:z66.string().optional(),waitForCompletion:z66.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z66.object({identifier:z66.string(),status:SandboxProcessStatusSchema,command:z66.string().optional(),startedAt:z66.string().optional(),exitCode:z66.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z66.object({processes:z66.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z66.object({processId:z66.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z66.object({success:z66.boolean(),message:z66.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z67}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_page_sources();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}cfg;static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path49,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env),fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers})}async rawRequest(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path49} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value,environment:input.environment})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentEnvs&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listEnvs(projectId,{includeAgentEnvs:!0}),current=branches.find(candidate=>candidate.env===branch),visited=new Set;for(;current&&!visited.has(current.env);){if(visited.add(current.env),current.resolvedEnvironment)return current.resolvedEnvironment.id;current=current.parentEnv?branches.find(candidate=>candidate.env===current?.parentEnv):void 0}return PREVIEW_ENVIRONMENT_KEY}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path49,opts={}){let qs=lazyFetchQs(opts.against,{path:path49});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.env&¶ms.set("env",opts.env),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
43
43
|
|
|
44
44
|
`);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
|
|
45
45
|
|
|
@@ -1187,7 +1187,8 @@ ${report}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(
|
|
|
1187
1187
|
${result.driftLines.map(l=>` ${l}`).join(`
|
|
1188
1188
|
`)}`,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){ui.info({command:"agents run",message:`Dispatch was skipped: ${result.skipped}`});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_api();init_config();init_project();async function agentRunsCommand(name,options){try{let 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 limit=options.limit??20,cfg=loadConfig(),api=new FimoApiClient(cfg),sessions;try{sessions=await api.listAgentSessions(projectId,{agentName:name,env:options.env,limit})}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}if(sessions.length===0){ui.info({command:"agents runs",message:`(no recent sessions for '${name}'${options.env?` on env '${options.env}'`:""})`});return}let rows=sessions.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,env:session.env,cost:`$${session.costUsd.toFixed(4)}`}));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:"env",label:"BRANCH"},{key:"cost",label:"COST"}],rows,cellStyle:__name((row2,column)=>{if(column==="status")return statusRole(row2.status);if(column==="cost")return"dim"},"cellStyle")})}catch(err){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=startedAt instanceof Date?startedAt: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=startedAt instanceof Date?startedAt:new Date(startedAt),ms=(endedAt instanceof Date?endedAt: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),after2=normalizeSecrets(config.secrets).filter(secret=>secret.key!==key);config.secrets=after2,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();init_scaffold();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(`
|
|
1189
1189
|
`)},"render")})}__name(listTemplatesCommand,"listTemplatesCommand");import fs11 from"node:fs";import path13 from"node:path";init_dist();init_api();init_auth();init_config();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 text3=fs11.readFileSync(policyPath,"utf8");return parseFimoConfig(text3,{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 api=new FimoApiClient(loadConfig()),context=await getProjectContext({cwd:projectRoot}),environment=await api.resolveProjectEnvironmentKey(projectId,context.env),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 api.listProjectIntegrations(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 api.getProjectIntegrationInfo(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 api.listProjectSecretEntries(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(`
|
|
1190
|
-
`)}__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("--env <env>","Target env (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)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").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 (the agent's final message); latest run unless --session is given").option("--session <id>","Target a specific session id").option("--env <env>","Pick the latest run on a specific env").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.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(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");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,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],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,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];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,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,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.env})}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.env}),{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(data2){return JSON.stringify(data2,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,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,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");init_dist();import fs12 from"node:fs";import path14 from"node:path";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");async function assetsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,env:ctx.env});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),options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset);let result=await api.listAssets(ctx.projectId,Object.keys(params).length>0?params:void 0);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsListCommand,"assetsListCommand");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let filePath=path14.resolve(cwd,file);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;formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),options.name&&formData.append("name",options.name),options.parentId&&formData.append("parentId",options.parentId),options.folderPath&&formData.append("folderPath",options.folderPath);let result=await api.uploadAsset(ctx.projectId,formData);ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,env:ctx.env});let result=await api.createFolder(ctx.projectId,name,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,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,env:ctx.env});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_ENV2="main";var ENV_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidEnv2(env){return typeof env!="string"||env.length===0||env.length>255||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX2.test(env)}__name(isValidEnv2,"isValidEnv");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(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(env);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(env)}.${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.env]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let branch=currentBranch2(root2),env=branch??DEFAULT_ENV2,tenantApiUrl=buildTenantApiUrl2(link.projectId,env,link.tenantApiBaseUrl);return{env,tenantApiUrl,source:branch?"branch":"fallback",values:buildLocalRuntimeEnv({tenantApiUrl,env}),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 root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,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 eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&branch!=="HEAD"&&isValidEnv2(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 parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,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_api();init_git();init_project_context();init_project();function envOverride(program2){return envOverrideFromCommand(program2)}__name(envOverride,"envOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),envs=await new FimoApiClient().withEnv(ctx.env).listEnvs(ctx.projectId,{includeDeleted:opts.verbose,includeAgentEnvs:opts.all});if(envs.length===0){ui.info({command:"branch",message:"(no envs yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:opts.verbose?[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"},{key:"preview",label:"PREVIEW"}]:[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:envs.map(e=>({env:e.env,status:e.status,parent:e.parentEnv??"\u2014",preview:opts.verbose?e.previewUrl??"":void 0})),isActive:__name(row2=>row2.env===ctx.env,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),parentEnv=opts.from??ctx.env;if(isProductionEnv(name)||isProductionEnv(parentEnv)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let created=await api.createEnv(ctx.projectId,{env:name,parentEnv});ui.ok({command:"branch",headline:`Created Branch '${created.env}' (status: ${created.status})`,details:{env:created.env,parent_env:parentEnv,status:created.status,preview_url:created.previewUrl??null}})}__name(branchCreateCommand,"branchCreateCommand");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env);if(name===DEFAULT_ENV){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default env '${DEFAULT_ENV}'.`});return}if(isProductionEnv(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be deleted.`});return}await api.deleteEnv(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd();if(isProductionEnv(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentEnv=opts.from??ctx.env,parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createEnv(ctx.projectId,{env:name,parentEnv}),created=!0}else await api.getEnv(ctx.projectId,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:{env:name,created,git_switched:gitSwitched,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 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({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),{env,conflicts}=await api.syncEnv(ctx.projectId,ctx.env,{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;ui.ok({command:"pull",headline:`Env '${env.env}' synced`,details:{env:env.env,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentEnv(api,projectId,parentEnv,ctx,fromFlag){try{return await api.getEnv(projectId,parentEnv),{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 env (\`${ctx.env}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.env}\`)`:ctx.source==="tag"?`the release tag \`${ctx.env}\``:`the project default (\`${ctx.env}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing env via \`--from <env>\` (try \`--from ${DEFAULT_ENV}\`)`):ctx.source==="branch"?(fixes.push(`switch envs first: \`fimo checkout ${DEFAULT_ENV}\``),fixes.push(`or pass \`--from ${DEFAULT_ENV}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--env <existing>\` (try \`--env ${DEFAULT_ENV}\`)`):fixes.push(`pass \`--from ${DEFAULT_ENV}\` to fork from main`),{ok:!1,message:`Cannot create env: parent env '${parentEnv}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentEnv,"validateParentEnv");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
|
|
1190
|
+
`)}__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("--env <env>","Target env (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)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").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 (the agent's final message); latest run unless --session is given").option("--session <id>","Target a specific session id").option("--env <env>","Pick the latest run on a specific env").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.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(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");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,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],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,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];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,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,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.env})}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.env}),{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(data2){return JSON.stringify(data2,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,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,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");init_dist();import fs12 from"node:fs";import path14 from"node:path";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");async function assetsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,env:ctx.env});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),options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset);let result=await api.listAssets(ctx.projectId,Object.keys(params).length>0?params:void 0);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsListCommand,"assetsListCommand");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let filePath=path14.resolve(cwd,file);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;formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),options.name&&formData.append("name",options.name),options.parentId&&formData.append("parentId",options.parentId),options.folderPath&&formData.append("folderPath",options.folderPath);let result=await api.uploadAsset(ctx.projectId,formData);ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,env:ctx.env});let result=await api.createFolder(ctx.projectId,name,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,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,env:ctx.env});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_ENV2="main";var ENV_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidEnv2(env){return typeof env!="string"||env.length===0||env.length>255||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX2.test(env)}__name(isValidEnv2,"isValidEnv");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(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(env);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(env)}.${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.env]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let branch=currentBranch2(root2),env=branch??DEFAULT_ENV2,tenantApiUrl=buildTenantApiUrl2(link.projectId,env,link.tenantApiBaseUrl);return{env,tenantApiUrl,source:branch?"branch":"fallback",values:buildLocalRuntimeEnv({tenantApiUrl,env}),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 root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,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 eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&branch!=="HEAD"&&isValidEnv2(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 parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,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_api();init_config();init_git();init_project_context();init_esm();function buildPreviewUrl(webUrl,projectId,env){return new URL(`/preview/${encodeURIComponent(projectId)}/${encodeEnvPathSegment(env)}`,webUrl).toString()}__name(buildPreviewUrl,"buildPreviewUrl");function buildProjectPreviewUrl(webUrl,projectId,env){return new URL(`/app/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(env)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();function envOverride(program2){return envOverrideFromCommand(program2)}__name(envOverride,"envOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),envs=await new FimoApiClient().withEnv(ctx.env).listEnvs(ctx.projectId,{includeDeleted:opts.verbose,includeAgentEnvs:opts.all});if(envs.length===0){ui.info({command:"branch",message:"(no envs yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:envs.map(e=>({env:e.env,status:e.status,parent:e.parentEnv??"\u2014"})),isActive:__name(row2=>row2.env===ctx.env,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),parentEnv=opts.from??ctx.env;if(isProductionEnv(name)||isProductionEnv(parentEnv)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let project=await api.getProject(ctx.projectId),created=await api.createEnv(ctx.projectId,{env:name,parentEnv}),previewUrl=project.previewEnabled===!1?null:buildPreviewUrl(loadConfig().webUrl,ctx.projectId,created.env),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,created.env),headline=`Created Branch '${created.env}' (status: ${created.status})`;ui.result({command:"branch",data:{headline,details:{env:created.env,parent_env:parentEnv,status:created.status,preview_url:previewUrl,studio_url:studioUrl,dashboard_url:studioUrl}},render:__name(context=>renderBranchCreated({headline,parentEnv,previewUrl,studioUrl},context),"render")})}__name(branchCreateCommand,"branchCreateCommand");function renderBranchCreated(result,context){let lines=[`${context.ascii?"[ok]":"\u2713"} ${result.headline}`,` Parent: ${result.parentEnv}`];return result.previewUrl&&lines.push(` Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),lines.push(` Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.join(`
|
|
1191
|
+
`)}__name(renderBranchCreated,"renderBranchCreated");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env);if(name===DEFAULT_ENV){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default env '${DEFAULT_ENV}'.`});return}if(isProductionEnv(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be deleted.`});return}await api.deleteEnv(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd();if(isProductionEnv(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentEnv=opts.from??ctx.env,parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createEnv(ctx.projectId,{env:name,parentEnv}),created=!0}else await api.getEnv(ctx.projectId,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:{env:name,created,git_switched:gitSwitched,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 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({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),{env,conflicts}=await api.syncEnv(ctx.projectId,ctx.env,{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;ui.ok({command:"pull",headline:`Env '${env.env}' synced`,details:{env:env.env,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentEnv(api,projectId,parentEnv,ctx,fromFlag){try{return await api.getEnv(projectId,parentEnv),{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 env (\`${ctx.env}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.env}\`)`:ctx.source==="tag"?`the release tag \`${ctx.env}\``:`the project default (\`${ctx.env}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing env via \`--from <env>\` (try \`--from ${DEFAULT_ENV}\`)`):ctx.source==="branch"?(fixes.push(`switch envs first: \`fimo checkout ${DEFAULT_ENV}\``),fixes.push(`or pass \`--from ${DEFAULT_ENV}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--env <existing>\` (try \`--env ${DEFAULT_ENV}\`)`):fixes.push(`pass \`--from ${DEFAULT_ENV}\` to fork from main`),{ok:!1,message:`Cannot create env: parent env '${parentEnv}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentEnv,"validateParentEnv");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
|
|
1191
1192
|
Examples:
|
|
1192
1193
|
fimo integrations connect slack
|
|
1193
1194
|
fimo channels bind slack:#launch
|
|
@@ -1198,7 +1199,7 @@ Run \`fimo channels <command> --help\` for command-specific help.
|
|
|
1198
1199
|
`)}__name(renderCreditsHuman,"renderCreditsHuman");async function creditsCommand(options){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId2(options),credits=await api.getProjectCredits(projectId);ui.result({command:"credits",data:credits,render:__name(()=>renderCreditsHuman(credits),"render")})}__name(creditsCommand,"creditsCommand");init_dist5();init_esm();init_dist();import fs24 from"node:fs";function skippedPhase(name,reason){return{name,ok:!1,errors:[],skipped:{reason}}}__name(skippedPhase,"skippedPhase");function allErrors(report){return[...report.phases.checks.errors,...report.phases.codegen.errors,...report.phases.sync.errors]}__name(allErrors,"allErrors");function computeExitCode(report){let errors=allErrors(report);return errors.some(e=>e.kind==="infra")?2:errors.some(e=>e.kind==="author")?1:0}__name(computeExitCode,"computeExitCode");function finalizeReport(report){let full={...report,ok:!1,exitCode:0};return full.exitCode=computeExitCode(full),full.ok=full.exitCode===0,full}__name(finalizeReport,"finalizeReport");function authorError(opts){return{kind:"author",...opts}}__name(authorError,"authorError");function infraErrorFromException(rule,error){return{kind:"infra",rule,message:error instanceof Error?error.message:String(error)}}__name(infraErrorFromException,"infraErrorFromException");function formatReportHuman(report){let lines=[];for(let phase of[report.phases.checks,report.phases.codegen,report.phases.sync])lines.push(formatPhaseHuman(phase));return lines.push(""),report.ok?lines.push("\u2713 All checks passed."):report.exitCode===1?lines.push("\u2717 Validation failed \u2014 fix the author errors above and re-run."):lines.push("\u2717 Infrastructure error \u2014 Fimo backend was unreachable or returned an error. Try again later."),lines.join(`
|
|
1199
1200
|
`)}__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(`
|
|
1200
1201
|
`)}__name(formatPhaseHuman,"formatPhaseHuman");init_api();init_config();init_auth_errors();init_templates();import fs16 from"node:fs";import path18 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=path18.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(!replaceLocalFimoSpecs(pkg,selection.version))return null;try{fs16.writeFileSync(selection.packagePath,JSON.stringify(pkg,null,2)+`
|
|
1201
|
-
`);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=path18.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 replaceLocalFimoSpecs(pkg,version){let changed=!1;for(let field of DEP_FIELDS){let deps=pkg[field];if(!deps)continue;let spec=deps.fimo;typeof spec=="string"&&spec.startsWith("file:")&&spec!==version&&(deps.fimo=version,changed=!0)}return changed}__name(replaceLocalFimoSpecs,"replaceLocalFimoSpecs");function resolveFileSpec(spec,cwd){let rawPath=spec.slice(5),packagePath=path18.isAbsolute(rawPath)?rawPath:path18.resolve(cwd,rawPath);return path18.resolve(packagePath)}__name(resolveFileSpec,"resolveFileSpec");function isInsideProject(cwd,targetPath){let relative3=path18.relative(path18.resolve(cwd),path18.resolve(targetPath));return relative3===""||!relative3.startsWith("..")&&!path18.isAbsolute(relative3)}__name(isInsideProject,"isInsideProject");init_environment_checkout();init_git_credential_setup();init_git();init_interactive();init_project_context();function buildProjectPreviewUrl(webUrl,projectId,env){return new URL(`/app/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(env)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();init_dist();import{readFile as readFile3}from"node:fs/promises";import path27 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{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}}catch{return defaultConfig}}__name(getConfigServer,"getConfigServer");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{join as join3}from"node:path";import{parseSync}from"oxc-parser";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=parseSync(parsePath,code2).program,fimoLabelNames=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,contents2)=>{let ast=parseSync(`${filePath}.ts`,contents2).program;for(let name of importedNames(ast.body,"fimo/sveltekit/components","Label"))labelNames.add(name);return declarations.push(...extractFromModule(filePath,contents2,`${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");init_sync_forms();init_sync_schemas();init_esm();import fs19 from"node:fs";import path22 from"node:path";init_esm();import fs18 from"node:fs";import path21 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=path21.join(cwd,"src/schemas");if(!fs18.existsSync(directory))return null;let schemas3=new Map;for(let file of fs18.readdirSync(directory).filter(name=>name.endsWith(".json"))){let fallbackUid=path21.basename(file,".json"),value;try{value=JSON.parse(fs18.readFileSync(path21.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[routeId2,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.${routeId2}.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.${routeId2}.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(!fs19.existsSync(configPath))return{errors:[],configChecked:!1};let displayPath=path22.relative(cwd,configPath).replaceAll(path22.sep,"/"),value;try{value=JSON.parse(fs19.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 fs20 from"node:fs";import path23 from"node:path";var FIMO_LOCALE_PARAM="locale";function normalizeRoutePath(path49){let collapsed=(path49.startsWith("/")?path49:`/${path49}`).replace(/\/{2,}/g,"/");return collapsed.length>1?collapsed.replace(/\/+$/,""):collapsed}__name(normalizeRoutePath,"normalizeRoutePath");function splitSegments(path49){return path49.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,index2,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(index2!==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 path49=normalizeRoutePath(route.path??"/"),segments=splitSegments(path49),declared=route.params??{},issues=[],params=[],unresolvedParams=[],seen=new Set;segments.forEach((segment,index2)=>{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,index2,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("/")}`):path49;return{id,config:route,path:path49,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 add2(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(add2,"add");function normalizePath(p2){return p2?`/${p2}`.replace(/^\/\//,"/"):"/"}__name(normalizePath,"normalizePath");for(let match of stripped.matchAll(/\bindex\(\s*['"]([^'"]+)['"](?:\s*,[^)]*)?\)/g))add2({path:"/",file:match[1],isIndex:!0});for(let match of stripped.matchAll(/\broute\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/g))add2({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\blayout\(\s*['"]([^'"]+)['"]/g))add2({path:null,file:match[1],isIndex:!1,isLayout:!0});for(let match of stripped.matchAll(/\{\s*path:\s*['"]([^'"]+)['"][^}]*?file:\s*['"]([^'"]+)['"][^}]*\}/g))add2({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);add2({path:pathMatch?normalizePath(pathMatch[1]):"/",file,isIndex})}return routes}__name(parseRoutesSource,"parseRoutesSource");function readJson(filePath){try{return JSON.parse(fs20.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=path23.relative(cwd,configFilePath).replaceAll(path23.sep,"/"),srcDir=path23.resolve(cwd,"src"),routesFilePath=path23.resolve(srcDir,"routes.ts"),errors=[],config=readJson(configFilePath),fileRoutes=[];if(!fs20.existsSync(routesFilePath))errors.push("Missing src/routes.ts.");else{let source=fs20.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}.
|
|
1202
|
+
`);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=path18.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 replaceLocalFimoSpecs(pkg,version){let changed=!1;for(let field of DEP_FIELDS){let deps=pkg[field];if(!deps)continue;let spec=deps.fimo;typeof spec=="string"&&spec.startsWith("file:")&&spec!==version&&(deps.fimo=version,changed=!0)}return changed}__name(replaceLocalFimoSpecs,"replaceLocalFimoSpecs");function resolveFileSpec(spec,cwd){let rawPath=spec.slice(5),packagePath=path18.isAbsolute(rawPath)?rawPath:path18.resolve(cwd,rawPath);return path18.resolve(packagePath)}__name(resolveFileSpec,"resolveFileSpec");function isInsideProject(cwd,targetPath){let relative3=path18.relative(path18.resolve(cwd),path18.resolve(targetPath));return relative3===""||!relative3.startsWith("..")&&!path18.isAbsolute(relative3)}__name(isInsideProject,"isInsideProject");init_environment_checkout();init_git_credential_setup();init_git();init_interactive();init_project_context();init_project();init_dist();import{readFile as readFile3}from"node:fs/promises";import path27 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{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}}catch{return defaultConfig}}__name(getConfigServer,"getConfigServer");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{join as join3}from"node:path";import{parseSync}from"oxc-parser";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=parseSync(parsePath,code2).program,fimoLabelNames=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,contents2)=>{let ast=parseSync(`${filePath}.ts`,contents2).program;for(let name of importedNames(ast.body,"fimo/sveltekit/components","Label"))labelNames.add(name);return declarations.push(...extractFromModule(filePath,contents2,`${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");init_sync_forms();init_sync_schemas();init_esm();import fs19 from"node:fs";import path22 from"node:path";init_esm();import fs18 from"node:fs";import path21 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=path21.join(cwd,"src/schemas");if(!fs18.existsSync(directory))return null;let schemas3=new Map;for(let file of fs18.readdirSync(directory).filter(name=>name.endsWith(".json"))){let fallbackUid=path21.basename(file,".json"),value;try{value=JSON.parse(fs18.readFileSync(path21.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[routeId2,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.${routeId2}.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.${routeId2}.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(!fs19.existsSync(configPath))return{errors:[],configChecked:!1};let displayPath=path22.relative(cwd,configPath).replaceAll(path22.sep,"/"),value;try{value=JSON.parse(fs19.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 fs20 from"node:fs";import path23 from"node:path";var FIMO_LOCALE_PARAM="locale";function normalizeRoutePath(path49){let collapsed=(path49.startsWith("/")?path49:`/${path49}`).replace(/\/{2,}/g,"/");return collapsed.length>1?collapsed.replace(/\/+$/,""):collapsed}__name(normalizeRoutePath,"normalizeRoutePath");function splitSegments(path49){return path49.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,index2,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(index2!==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 path49=normalizeRoutePath(route.path??"/"),segments=splitSegments(path49),declared=route.params??{},issues=[],params=[],unresolvedParams=[],seen=new Set;segments.forEach((segment,index2)=>{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,index2,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("/")}`):path49;return{id,config:route,path:path49,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 add2(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(add2,"add");function normalizePath(p2){return p2?`/${p2}`.replace(/^\/\//,"/"):"/"}__name(normalizePath,"normalizePath");for(let match of stripped.matchAll(/\bindex\(\s*['"]([^'"]+)['"](?:\s*,[^)]*)?\)/g))add2({path:"/",file:match[1],isIndex:!0});for(let match of stripped.matchAll(/\broute\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/g))add2({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\blayout\(\s*['"]([^'"]+)['"]/g))add2({path:null,file:match[1],isIndex:!1,isLayout:!0});for(let match of stripped.matchAll(/\{\s*path:\s*['"]([^'"]+)['"][^}]*?file:\s*['"]([^'"]+)['"][^}]*\}/g))add2({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);add2({path:pathMatch?normalizePath(pathMatch[1]):"/",file,isIndex})}return routes}__name(parseRoutesSource,"parseRoutesSource");function readJson(filePath){try{return JSON.parse(fs20.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=path23.relative(cwd,configFilePath).replaceAll(path23.sep,"/"),srcDir=path23.resolve(cwd,"src"),routesFilePath=path23.resolve(srcDir,"routes.ts"),errors=[],config=readJson(configFilePath),fileRoutes=[];if(!fs20.existsSync(routesFilePath))errors.push("Missing src/routes.ts.");else{let source=fs20.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}.
|
|
1202
1203
|
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.
|
|
1203
1204
|
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}
|
|
1204
1205
|
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=path23.resolve(srcDir,file);if(!fs20.existsSync(routeModulePath)){errors.push(`Route "${route.id}" (${route.path}) references missing module "${file}".
|
|
@@ -1238,7 +1239,7 @@ This breaks source tracking for inline editing. Translation keys must be statica
|
|
|
1238
1239
|
`),process.exit(1)}}import fs23 from"node:fs";import path26 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(!fs23.existsSync(dir))return files;let entries2=fs23.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(SKIP_DIRS.has(entry.name))continue;let fullPath=path26.join(dir,entry.name);entry.isDirectory()?files.push(...collectFiles(fullPath)):SCAN_EXTENSIONS_SET.has(path26.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=path26.resolve(srcDir,specifier.slice(2));else if(specifier.startsWith("."))targetPath=path26.resolve(fromDir,specifier);else return null;if(fs23.existsSync(targetPath)&&fs23.statSync(targetPath).isFile())return targetPath;for(let ext of SCAN_EXTENSIONS){let withExt=targetPath+ext;if(fs23.existsSync(withExt))return withExt}for(let ext of SCAN_EXTENSIONS){let indexFile=path26.join(targetPath,"index"+ext);if(fs23.existsSync(indexFile))return indexFile}return null}__name(resolveImport,"resolveImport");function discoverRoutes(srcDir,root2){let routesFilePath=path26.resolve(srcDir,"routes.ts");if(!fs23.existsSync(routesFilePath))return new Map;let source=fs23.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=path26.relative(root2,resolved);fileToRoutes.has(rel)||fileToRoutes.set(rel,new Set),fileToRoutes.get(rel).add(r.path)}return fileToRoutes}__name(discoverRoutes,"discoverRoutes");function buildReverseImportGraph(srcDir,root2){let fileToImporters=new Map,allFiles=collectFiles(srcDir);for(let filePath of allFiles){let content2;try{content2=fs23.readFileSync(filePath,"utf-8")}catch{continue}let imports=extractImports(content2);for(let specifier of imports){let resolved=resolveImport(specifier,path26.dirname(filePath),srcDir);if(!resolved)continue;let resolvedRel=path26.relative(root2,resolved),importerRel=path26.relative(root2,filePath);fileToImporters.has(resolvedRel)||fileToImporters.set(resolvedRel,new Set),fileToImporters.get(resolvedRel).add(importerRel)}}return fileToImporters}__name(buildReverseImportGraph,"buildReverseImportGraph");function resolveAffectedRoutes(file,fileToImporters,fileToRoutes){let visited=new Set,queue=[file],affectedRoutes=new Set;for(;queue.length>0;){let current=queue.shift();if(visited.has(current))continue;visited.add(current);let routes=fileToRoutes.get(current);if(routes)for(let route of routes)affectedRoutes.add(route);let importers=fileToImporters.get(current);if(importers)for(let importer of importers)visited.has(importer)||queue.push(importer)}return Array.from(affectedRoutes)}__name(resolveAffectedRoutes,"resolveAffectedRoutes");function resolveRoutes(changedFiles,options={}){let root2=options.cwd??process.cwd(),srcDir=path26.resolve(root2,"src"),normalizedChangedFiles=changedFiles.map(f=>f.replace(/^\/+/,""));if(normalizedChangedFiles.length===0)return{routeMap:{},routes:[],unresolvedFiles:[]};let fileToRoutes=discoverRoutes(srcDir,root2),fileToImporters=buildReverseImportGraph(srcDir,root2),routeMap={},unresolvedFiles=[];for(let file of normalizedChangedFiles){if(isGlobalFile(file)){routeMap[file]=["*"];continue}let routes=resolveAffectedRoutes(file,fileToImporters,fileToRoutes);routes.length>0?routeMap[file]=routes:unresolvedFiles.push(file)}let allRoutes=[...new Set(Object.values(routeMap).flat().filter(r=>r!=="*"))];return{routeMap,routes:allRoutes,unresolvedFiles}}__name(resolveRoutes,"resolveRoutes");init_sync_forms();init_sync_schemas();function resolveCwd(options){return options.cwd?resolve7(options.cwd):process.cwd()}__name(resolveCwd,"resolveCwd");function renderPrettyJson4(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson4,"renderPrettyJson");async function syncSchemasCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncSchemas({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-schemas",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncSchemasCommand,"syncSchemasCommand");async function syncFormsCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncForms({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-forms",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncFormsCommand,"syncFormsCommand");async function exportStaticCommand(options){let result=await exportStatic({cwd:resolveCwd(options)});ui.result({command:"export-static",data:result??{ok:!0},render:__name(()=>renderPrettyJson4(result??{ok:!0}),"render")})}__name(exportStaticCommand,"exportStaticCommand");function validateRouteMetadataCommand(options){let result=validateRouteMetadata({cwd:resolveCwd(options)});result.errors.length>0&&(ui.error({command:"scripts validate-route-metadata",code:"ROUTE_METADATA_INVALID",message:`Route metadata validation failed (${result.errors.length} issue(s)):
|
|
1239
1240
|
${result.errors.map(e=>` - ${e}`).join(`
|
|
1240
1241
|
`)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data2={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data:data2,render:__name(()=>JSON.stringify(data2),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root2){if(!existsSync8(root2))return[];let results=[];for(let name of readdirSync6(root2)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root2,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),envOverride2=envOverrideFromCommand(cmd),report=await runValidate({cwd,envOverride:envOverride2}),warnings=[getDbLabelsRuntimeWarning(cwd)].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,envOverride:envOverride2}=opts,checks=await runChecksPhase({cwd}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,envOverride:envOverride2}),finalizeReport({phases:{checks,codegen,sync}})}__name(runValidate,"runValidate");async function runChecksPhase(opts){let{cwd}=opts,[lintResult,routeResult,agentsResult,schemasResult,configResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd})),Promise.resolve().then(()=>validateFimoConfig(cwd))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));if(configResult.status==="fulfilled"){stats.configsChecked=Number(configResult.value.configChecked);for(let message of configResult.value.errors)errors.push(authorError({rule:"fimo-config",message}))}else errors.push(infraErrorFromException("fimo-config",configResult.reason));return{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");async function runRouteMetadataCheck(opts){let framework=await detectProjectFramework(opts.cwd);return framework&&framework.slug!=="react-router"?null:validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,frameworkResult=detectProjectFramework(cwd),[schemasResult,formsResult,labelsResult]=await Promise.allSettled([frameworkResult.then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),frameworkResult.then(framework=>syncForms({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,envOverride:envOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,envOverride:envOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let api=new FimoApiClient(loadConfig()).withEnv(ctx.env),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(()=>api.listLabels(ctx.projectId,locale),"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Env":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path27.join(cwd,".env")),...await readEnvFile(path27.join(cwd,".env.local"))};if(process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),!values.VITE_API_URL){let derived=resolveLocalRuntimeEnv({cwd});derived&&(values.VITE_API_URL=derived.tenantApiUrl,values.FIMO_ENV??=derived.env)}return values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index2=trimmed.indexOf("=");if(index2===-1)continue;let key=trimmed.slice(0,index2).trim(),value=trimmed.slice(index2+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){if(process.env.FIMO_MIGRATION_NO_DEPLOY==="1"){ui.error({command:"deploy",code:"MIGRATION_DEPLOY_BLOCKED",message:"Deployment is disabled while a migration is running.",hint:"Finish local migration and QA first, then request deployment separately."});return}let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let envOverride2=envOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,envOverride:envOverride2});if(isPretty2&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
1241
|
-
`),ctx.readOnly){ui.error({command:"deploy",code:"ENV_READONLY",message:`Refusing to deploy to read-only env '${ctx.env}'.`,hint:"Switch off the release/* tag or pass --env <writable-env>."});return}if(options.publish&&ctx.env!==DEFAULT_ENV){ui.error({command:"deploy",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to --publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:`Drop --publish to deploy a preview, or switch to '${DEFAULT_ENV}' first.`});return}let devFimoSelection;try{devFimoSelection=resolveDevFimoDependencyForDeploy(cwd)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}await requireOperation("fimo.deploy",{projectId:ctx.projectId,env:ctx.env});let cfg=loadConfig(),api=new FimoApiClient(cfg).withEnv(ctx.env),
|
|
1242
|
+
`),ctx.readOnly){ui.error({command:"deploy",code:"ENV_READONLY",message:`Refusing to deploy to read-only env '${ctx.env}'.`,hint:"Switch off the release/* tag or pass --env <writable-env>."});return}if(options.publish&&ctx.env!==DEFAULT_ENV){ui.error({command:"deploy",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to --publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:`Drop --publish to deploy a preview, or switch to '${DEFAULT_ENV}' first.`});return}let devFimoSelection;try{devFimoSelection=resolveDevFimoDependencyForDeploy(cwd)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}await requireOperation("fimo.deploy",{projectId:ctx.projectId,env:ctx.env});let cfg=loadConfig(),api=new FimoApiClient(cfg).withEnv(ctx.env),studioUrl=buildProjectPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewUrl=buildPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewEnabled=(await api.getProject(local.projectId)).previewEnabled!==!1,remoteSp=spinner("Checking the Fimo branch"),remote;try{remote=await api.getGitRemote(local.projectId,ctx.env),await ensureFimoRemote(cwd,remote.url);let preparation=await prepareDeployCheckout({cwd,remoteBranch:remote.branch});remoteSp.succeed(preparation==="missing-remote"?`Fimo branch ${remote.branch} will be created by this deploy`:`Checkout ready for fimo/${remote.branch}`)}catch(error){if(remoteSp.fail("Checkout is not ready to deploy"),error instanceof EnvironmentCheckoutError){ui.error({command:"deploy",code:error.code,message:error.message,hint:error.hint});return}rethrowCliAuthError(error),ui.error({command:"deploy",code:"ENV_GIT_PREFLIGHT_FAILED",message:`Could not compare this checkout with the Fimo branch: ${errorMessage(error)}`});return}let validateSp=spinner("Validating project"),report=await runValidate({cwd,envOverride:envOverride2});if(report.ok)validateSp.succeed("Validation passed");else if(options.force)validateSp.fail("Validation failed \u2014 continuing anyway (--force)"),ui.warn({command:"deploy",message:"Bypassing validation errors because --force was passed. The deploy may still fail later in the sandbox."});else{validateSp.fail("Validation failed"),ui.result({command:"deploy",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}let devFimoDependency=null;try{devFimoDependency=prepareDevFimoDependencyForDeploy(cwd,devFimoSelection)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}devFimoDependency&&isPretty2&&O2.info(`Deploying with fimo ${devFimoDependency.version}; restoring local dependency state after push.`);try{if(await hasUncommittedChanges(cwd)){let message;if(options.message!==void 0)message=options.message;else{assertInteractive('Pass -m "<message>" or commit your changes manually.',"deploy"),isPretty2&&O2.warn("You have uncommitted changes. Commit them before deploying.");let answer=await Ot({message:"Commit message",placeholder:"Deploy",defaultValue:"Deploy"});if(q(answer)){ui.info({command:"deploy",message:"Cancelled."});return}message=String(answer)}let commitSp=spinner("Committing pending changes");await runGit(["add","-A"],cwd),await runGit(["commit","-m",message],cwd),commitSp.succeed("Changes committed")}let remoteBranch=remote.branch,pushSp=spinner(`Pushing to fimo/${remoteBranch}`);try{await runGit(["push","fimo",`HEAD:${remoteBranch}`],cwd),pushSp.succeed("Pushed to Fimo")}catch(error){pushSp.fail("Push failed");let failure=classifyPushError(error);emitPushFailure(failure,remoteBranch);return}}finally{devFimoDependency?.restore()}let stepLabel="",stepStartedAt=0,stepSp=null,finalizeStep=__name((status="ok",failMessage)=>{if(!stepSp)return;let elapsed=((Date.now()-stepStartedAt)/1e3).toFixed(1);status==="ok"?stepSp.succeed(`${stepLabel} (${elapsed}s)`):stepSp.fail(failMessage??`${stepLabel} failed`),stepSp=null},"finalizeStep");try{await api.sandboxPull(local.projectId,({message})=>{finalizeStep("ok"),stepLabel=message,stepStartedAt=Date.now(),stepSp=spinner(message)},ctx.env,{noRestart:options.restart===!1}),finalizeStep("ok")}catch(error){rethrowCliAuthError(error,()=>finalizeStep("fail","Authentication required")),finalizeStep("fail",`Sandbox sync failed: ${errorMessage(error)}`),ui.error({command:"deploy",code:"SANDBOX_SYNC_FAILED",message:`Sandbox sync failed: ${errorMessage(error)}`});return}await syncDisplayNameIfRenamed({cwd,projectId:local.projectId,api});let sandboxUrl=null,sandboxExpiresAt=null;if(previewEnabled)try{let preview=await api.getPreviewUrl(local.projectId,ctx.env);sandboxUrl=preview.url,sandboxExpiresAt=preview.expiresAt}catch(error){isPretty2&&O2.warn(`Could not fetch preview URL: ${errorMessage(error)}`)}if(!options.publish){ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewEnabled?previewUrl:null,sandbox_url:sandboxUrl,sandbox_expires_at:sandboxExpiresAt,studio_url:studioUrl,dashboard_url:studioUrl,published:!1},render:__name(context=>renderDeployResult({previewUrl:previewEnabled?previewUrl:null,studioUrl,appUrl:null,previewEnabled,published:!1},context),"render")});return}let publishSp=spinner("Publishing (this can take a few minutes)");try{await api.publishProject(local.projectId)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail(),ui.error({command:"deploy",code:"PUBLISH_FAILED",message:`Publish failed: ${errorMessage(error)}`});return}publishSp.succeed("Published");let appUrl=null;try{appUrl=(await api.getProject(local.projectId)).appUrl}catch(error){isPretty2&&O2.warn(`Could not fetch published URL: ${errorMessage(error)}`)}ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewEnabled?previewUrl:null,sandbox_url:sandboxUrl,sandbox_expires_at:sandboxExpiresAt,studio_url:studioUrl,dashboard_url:studioUrl,published:!0,app_url:appUrl},render:__name(context=>renderDeployResult({previewUrl:previewEnabled?previewUrl:null,studioUrl,appUrl,previewEnabled,published:!0},context),"render")})}__name(deployCommand,"deployCommand");function renderDeployResult(result,context){let lines=[];return result.previewUrl&&lines.push(`Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),result.appUrl&&lines.push(`Live: ${terminalLink("Open site",result.appUrl,context.hyperlinks)}`),lines.push(`Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),result.published?lines.push(result.appUrl?"Your site is live.":"Publish completed. Check Fimo for the live URL."):lines.push(result.previewEnabled?"Deployed to preview. Run `fimo deploy --publish` or `fimo publish` to publish a new version.":"Changes synced. Preview is disabled for this project."),lines.join(`
|
|
1242
1243
|
`)}__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\`:
|
|
1243
1244
|
1. git pull --rebase fimo ${env}
|
|
1244
1245
|
2. resolve any conflicts, then \`git add\` + \`git rebase --continue\`
|
|
@@ -1364,8 +1365,9 @@ Remote config and local checkout are synchronized.`}__name(renderMutationResult,
|
|
|
1364
1365
|
`)}__name(renderModelHuman,"renderModelHuman");init_dist();init_api();init_auth();init_config();async function orgsListCommand(){let cfg=loadConfig(),api=new FimoApiClient(cfg),activeId=requireCredentials(cfg)?.activeOrganization?.id,orgs2=await api.listOrganizations();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(),api=new FimoApiClient(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 api.listOrganizationMembers(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_api();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 contentParams=pageContentParamNames(route.path??"");return contentParams.length===0?"static":route.params&&contentParams.every(param=>route.params?.[param])?"dynamic:bound":"dynamic:unbound"}__name(pageStatus,"pageStatus");function entryFieldValue(entry,field){if(entry[field]!==void 0)return entry[field];let data2=entry.data;if(data2&&typeof data2=="object")return data2[field]}__name(entryFieldValue,"entryFieldValue");function responseRows(response){if(Array.isArray(response))return response;if(!response||typeof response!="object")return[];let data2=response.data;return Array.isArray(data2)?data2:data2&&typeof data2=="object"&&Array.isArray(data2.data)?data2.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 filters2={};query.where&&Object.keys(query.where).length>0&&(filters2.where=JSON.stringify(query.where)),query.search&&(filters2.search=query.search);for(let[key,value]of[["sort",fieldList2(query.sort)],["fields",fieldList2(query.fields)],["populate",fieldList2(query.populate)]])value.length>0&&(filters2[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,{...filters2,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)}
|
|
1365
1366
|
`)}__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(`
|
|
1366
1367
|
`),"render")});return}let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});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(api,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(`
|
|
1367
|
-
`),"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 next2={...existing??{}};if(existing?.content){let normalizedSources=normalizedPageSources(existing);Object.keys(normalizedSources).length>0&&(next2.sources=normalizedSources),delete next2.content}if(options.path!==void 0&&(next2.path=options.path),options.label!==void 0&&(options.label===""?delete next2.label:next2.label=options.label),options.group!==void 0&&(options.group===""?delete next2.group:next2.group=options.group),options.icon!==void 0&&(options.icon===""?delete next2.icon:next2.icon=options.icon),options.sources!==void 0&&(next2.sources=parseSources(options.sources)),options.clearSources&&delete next2.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)),next2.params=params}if(options.clearParams&&delete next2.params,options.path!==void 0&&options.params===void 0&&!options.clearParams&&next2.params){let bindableParams=new Set(pageContentParamNames(next2.path??"")),retainedParams=Object.fromEntries(Object.entries(next2.params).filter(([param])=>bindableParams.has(param)));Object.keys(retainedParams).length>0?next2.params=retainedParams:delete next2.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,api}=await projectContextPromise;await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let schema;try{schema=await api.getSchema(ctx.projectId,schemaName)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==404)throw error;schema=null}return schemas3.set(schemaName,schema),schema},"getSchema"),effectivePath=next2.path??"",contentParams=pageContentParamNames(effectivePath),effectiveParams=next2.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(next2.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]=next2,writePageRegistry(file,config,routes),ui.result({command:"pages set",data:{id,page:next2},render:__name(()=>`Page "${id}" now points to ${next2.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(([routeId2,route])=>[routeId2===id?nextId:routeId2,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_dist();init_config();init_project_context();function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");async function previewUrlCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);if(await requireOperation("fimo.preview.url",{projectId:ctx.projectId,env:ctx.env}),(await api.getProject(ctx.projectId)).previewEnabled===!1){ui.error({command:"preview url",code:"PREVIEW_DISABLED",message:"Preview is disabled for this project.",hint:"Turn off Disable Preview in Project settings before requesting a preview URL."});return}
|
|
1368
|
-
`)
|
|
1368
|
+
`),"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 next2={...existing??{}};if(existing?.content){let normalizedSources=normalizedPageSources(existing);Object.keys(normalizedSources).length>0&&(next2.sources=normalizedSources),delete next2.content}if(options.path!==void 0&&(next2.path=options.path),options.label!==void 0&&(options.label===""?delete next2.label:next2.label=options.label),options.group!==void 0&&(options.group===""?delete next2.group:next2.group=options.group),options.icon!==void 0&&(options.icon===""?delete next2.icon:next2.icon=options.icon),options.sources!==void 0&&(next2.sources=parseSources(options.sources)),options.clearSources&&delete next2.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)),next2.params=params}if(options.clearParams&&delete next2.params,options.path!==void 0&&options.params===void 0&&!options.clearParams&&next2.params){let bindableParams=new Set(pageContentParamNames(next2.path??"")),retainedParams=Object.fromEntries(Object.entries(next2.params).filter(([param])=>bindableParams.has(param)));Object.keys(retainedParams).length>0?next2.params=retainedParams:delete next2.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,api}=await projectContextPromise;await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let schema;try{schema=await api.getSchema(ctx.projectId,schemaName)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==404)throw error;schema=null}return schemas3.set(schemaName,schema),schema},"getSchema"),effectivePath=next2.path??"",contentParams=pageContentParamNames(effectivePath),effectiveParams=next2.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(next2.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]=next2,writePageRegistry(file,config,routes),ui.result({command:"pages set",data:{id,page:next2},render:__name(()=>`Page "${id}" now points to ${next2.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(([routeId2,route])=>[routeId2===id?nextId:routeId2,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_dist();init_config();init_project_context();function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");async function previewUrlCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);if(await requireOperation("fimo.preview.url",{projectId:ctx.projectId,env:ctx.env}),(await api.getProject(ctx.projectId)).previewEnabled===!1){ui.error({command:"preview url",code:"PREVIEW_DISABLED",message:"Preview is disabled for this project.",hint:"Turn off Disable Preview in Project settings before requesting a preview URL."});return}let mode2=currentMode(),isInteractive2=mode2.format==="pretty"&&isTtyStream(mode2.stdout),previewUrl=buildPreviewUrl(loadConfig().webUrl,ctx.projectId,ctx.env),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,ctx.env);if(isInteractive2&&!options.all){ui.result({command:"preview url",data:{project_id:ctx.projectId,env:ctx.env,preview_url:previewUrl,sandbox_url:null,sandbox_expires_at:null,studio_url:studioUrl,dashboard_url:studioUrl},render:__name(context=>[`Preview: ${terminalLink("Open preview",previewUrl,context.hyperlinks)}`,`Studio: ${terminalLink("Open in Studio",studioUrl,context.hyperlinks)}`].join(`
|
|
1369
|
+
`),"render")});return}try{let session=await api.getPreviewUrl(ctx.projectId,ctx.env);ui.result({command:"preview url",data:{project_id:ctx.projectId,env:ctx.env,preview_url:previewUrl,sandbox_url:session.url,sandbox_expires_at:session.expiresAt,studio_url:studioUrl,dashboard_url:studioUrl},render:__name(()=>options.all?[`Preview: ${previewUrl}`,`Studio: ${studioUrl}`,`Sandbox: ${session.url}`,`Expires: ${session.expiresAt}`].join(`
|
|
1370
|
+
`):session.url,"render")})}catch(error){ui.error({command:"preview url",code:"PREVIEW_URL_FAILED",message:`Failed to get preview URL: ${errorMessage2(error)}`})}}__name(previewUrlCommand,"previewUrlCommand");function registerPreviewCommands(program2){program2.command("preview").description("Inspect a Branch preview without deploying").command("url").description("Get a fresh preview URL for the current Branch (or --branch <name>) without deploying").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--all","Show the Preview, Studio, and raw sandbox destinations").action((opts,cmd)=>previewUrlCommand(opts,cmd))}__name(registerPreviewCommands,"registerPreviewCommands");init_esm();init_dist();init_api();init_config();import fs43 from"node:fs";import path44 from"node:path";function mergeManagedEnvBlock(existing,entries2,spec){let block=renderBlock(entries2,spec),normalized=existing.replace(/\r\n/g,`
|
|
1369
1371
|
`),lines=normalized.endsWith(`
|
|
1370
1372
|
`)?normalized.slice(0,-1).split(`
|
|
1371
1373
|
`):normalized.split(`
|
|
@@ -1433,7 +1435,7 @@ Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=lite
|
|
|
1433
1435
|
`);addScopeOptions4(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions4(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand5(opts,command)),addScopeOptions4(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect3).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id","main").option("--debounce-changes <immediate|5s|30s|1m>","Combine rapid entry.changed events into one delivery").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand4(name,opts,command)),addScopeOptions4(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect3).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id").option("--debounce-changes <immediate|5s|30s|1m>","Change the entry.changed debounce window").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries").option("--limit <count>","Maximum deliveries to return (1-100)")).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope5(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,env:ctx.env}}return await requireOperation(op,scope),{...scope,api:new FimoApiClient(loadConfig())}}__name(resolveScope5,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope5("webhooks.events",opts,command),events=await api.listWebhookEvents(projectId);if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand5(opts,command){let{api,projectId}=await resolveScope5("webhooks.list",opts,command),webhooks=await api.listProjectWebhooks(projectId);ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand5,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.get",opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand4(name,opts,command){let{api,projectId}=await resolveScope5("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1,entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges??(opts.event==="entry.changed"?"5s":"immediate"))});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await api.createProjectWebhook(projectId,parsed.data);renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand4,"createCommand");async function updateCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await api.getProjectWebhook(projectId,webhookId),filter4=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter4?{filter:filter4}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{},...opts.debounceChanges!==void 0?{entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges)}:opts.event==="entry.changed"&¤t.eventType!=="entry.changed"?{entryBatchWindowSeconds:5}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await api.updateProjectWebhook(projectId,webhookId,parsed.data))}__name(updateCommand3,"updateCommand");async function deleteCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.delete",opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand3,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.test",opts,command),data2=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await api.testProjectWebhook(projectId,webhookId,{data:data2});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await api.getProjectWebhookDelivery(projectId,webhookId,delivery.id)).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.list",opts,command),limit=opts.limit===void 0?void 0:parseLimit2(opts.limit),deliveries=await api.listProjectWebhookDeliveries(projectId,webhookId,limit);ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows:deliveries.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)}))})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await api.getProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.rotate_secret",opts,command),signingSecret=await api.rotateProjectWebhookSecret(projectId,webhookId);renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function parseEntryBatchWindow(value){let parsed={immediate:0,"5s":5,"30s":30,"1m":60}[value.toLowerCase()];if(parsed===void 0)throw new WebhookCommandError("WEBHOOK_GROUPING_INVALID",`Invalid grouping window '${value}'. Use immediate, 5s, 30s, or 1m.`);return parsed}__name(parseEntryBatchWindow,"parseEntryBatchWindow");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path49=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile5(path49,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path49}'.`)}}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 parseLimit2(value){let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>100)throw new WebhookCommandError("WEBHOOK_LIMIT_INVALID","--limit must be an integer from 1 to 100.");return limit}__name(parseLimit2,"parseLimit");function renderJson(command,data2){ui.result({command,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["environments","status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
|
|
1434
1436
|
`)}__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(`
|
|
1435
1437
|
`).map(line=>` ${line}`).join(`
|
|
1436
|
-
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs47.readFileSync(path48.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(fs47.readFileSync(path48.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--env <name>","Override the env this command targets (defaults to the current git branch, falling back to `main`)").option("--branch <name>","Override the Fimo Branch this command targets (legacy alias: `--env`)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("mcp").description("Serve the Fimo MCP server over stdio (for MCP clients such as Claude Code or Cursor)").action(mcpCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--env <name>","Env to link (defaults to the current git branch, else main)").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--env <name>","Env to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Set up the migration target: crawl a live site into draft artifacts, or link/create the Fimo project for a source-backed migration").argument("[target]","Published source site URL to crawl, or a target project directory for a source-backed migration").argument("[dir]","Target Fimo project directory for a URL migration (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--project-id <projectId>","Link an owner-supplied existing project (source-backed migration; delegates to `fimo init`)").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action(migrateInitCommand);migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the URL migration manifest, or of the canonical .fimo/migration ledger").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the URL-crawl draft manifest (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the URL-crawl draft toward the source site (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print the import plan as regular Fimo CLI commands; writes no data").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Show preview URLs + deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1438
|
+
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs47.readFileSync(path48.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(fs47.readFileSync(path48.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--env <name>","Override the env this command targets (defaults to the current git branch, falling back to `main`)").option("--branch <name>","Override the Fimo Branch this command targets (legacy alias: `--env`)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("mcp").description("Serve the Fimo MCP server over stdio (for MCP clients such as Claude Code or Cursor)").action(mcpCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--env <name>","Env to link (defaults to the current git branch, else main)").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--env <name>","Env to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Set up the migration target: crawl a live site into draft artifacts, or link/create the Fimo project for a source-backed migration").argument("[target]","Published source site URL to crawl, or a target project directory for a source-backed migration").argument("[dir]","Target Fimo project directory for a URL migration (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--project-id <projectId>","Link an owner-supplied existing project (source-backed migration; delegates to `fimo init`)").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action(migrateInitCommand);migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the URL migration manifest, or of the canonical .fimo/migration ledger").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the URL-crawl draft manifest (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the URL-crawl draft toward the source site (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print the import plan as regular Fimo CLI commands; writes no data").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Include deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1437
1439
|
Supported agents:
|
|
1438
1440
|
Universal (always covered via AGENTS.md, no per-agent file needed):
|
|
1439
1441
|
Codex, OpenCode, Aider, and other AGENTS.md-native tools
|