fimo 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 process8.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process8.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
40
40
  `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path54.basename(filename,path54.extname(filename)),this}executableDir(path55){return path55===void 0?this._executableDir:(this._executableDir=path55,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process8.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
41
41
  Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
42
- `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{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","Pro"]),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"}});import{z as z5}from"zod";var MB,MAX_DOCUMENT_SIZE_BYTES,MAX_AUDIO_SIZE_BYTES,MAX_IMAGE_SIZE_BYTES,MAX_VIDEO_SIZE_BYTES,MAX_ARCHIVE_SIZE_BYTES,MAX_MODEL_SIZE_BYTES,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES,MODEL_MEDIA_TYPE,AttachmentModelMediaTypeSchema,MODEL_MIME_TYPES,MODEL_RENDER_VIEW_ANGLES,AttachmentModelRenderRequestSchema,AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema,AttachmentModelRenderResponseSchema,AttachmentModelRenderMeterSchema,ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";MB=1024*1024,MAX_DOCUMENT_SIZE_BYTES=5*MB,MAX_AUDIO_SIZE_BYTES=10*MB,MAX_IMAGE_SIZE_BYTES=20*MB,MAX_VIDEO_SIZE_BYTES=20*MB,MAX_ARCHIVE_SIZE_BYTES=20*MB,MAX_MODEL_SIZE_BYTES=20*MB,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES=20*MB,MODEL_MEDIA_TYPE={GLB:"model/gltf-binary",GLTF:"model/gltf+json",FBX:"model/fbx",OBJ:"model/obj",STL:"model/stl",PLY:"model/ply"},AttachmentModelMediaTypeSchema=z5.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z5.object({renderId:z5.uuid(),filename:z5.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z5.url()}),AttachmentModelRenderSuccessSchema=z5.object({status:z5.literal("succeeded"),views:z5.tuple([z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z5.url()})]),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative(),diagnostics:z5.unknown().optional()}),AttachmentModelRenderFailureSchema=z5.object({status:z5.literal("failed"),error:z5.literal("render_failed"),message:z5.string(),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative()}),AttachmentModelRenderResponseSchema=z5.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z5.object({browserElapsedMs:z5.number().nonnegative()}),ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:MAX_ARCHIVE_SIZE_BYTES},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLB,extensions:[".glb"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLTF,extensions:[".gltf"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.FBX,extensions:[".fbx"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.OBJ,extensions:[".obj"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.STL,extensions:[".stl"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.PLY,extensions:[".ply"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z6}from"zod";var AssetReadRequestSchema,AssetDerivedFileSchema,AssetReadBaseSchema,AssetReadPageSchema,AssetReadQuerySchema,AssetReadResultSchema,init_asset_reading=__esm({"../../packages/api-contracts/dist/esm/types/asset-reading.js"(){"use strict";AssetReadRequestSchema=z6.object({cursor:z6.string().optional(),query:z6.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),AssetDerivedFileSchema=z6.object({url:z6.url(),mediaType:z6.string(),filename:z6.string()}),AssetReadBaseSchema=z6.object({assetId:z6.uuid(),filename:z6.string(),mediaType:z6.string(),representation:z6.enum(["text","table","document","archive","image","transcript","video","model"]),content:z6.string(),derivedFiles:z6.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z6.literal("page"),start:z6.number().int().nonnegative(),end:z6.number().int().nonnegative(),total:z6.number().int().nonnegative(),nextCursor:z6.string().nullable(),complete:z6.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z6.literal("query"),query:z6.string(),source:z6.enum(["original-file","canonical-text","derived-files"]),truncated:z6.boolean()}),AssetReadResultSchema=z6.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z7}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=z7.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 z8}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=z8.union([z8.literal(PRODUCTION_ENVIRONMENT_KEY),z8.literal(PREVIEW_ENVIRONMENT_KEY),z8.uuid()]),CustomEnvironmentSchema=z8.object({id:z8.uuid(),projectId:z8.uuid(),name:z8.string().trim().min(1).max(64),branchPatterns:z8.array(z8.string().min(1).max(255)).min(1),description:z8.string().max(255).nullable()}),ResolvedEnvironmentSchema=z8.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});import{z as z9}from"zod";var NOTIFICATION_EVENTS,NotificationAudienceSchema,NotificationEventSchema,init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env();NOTIFICATION_EVENTS={created:"notifications/created",stateChanged:"notifications/state-changed",unreadChanged:"notifications/unread-changed"},NotificationAudienceSchema=z9.object({projectId:z9.uuid(),userId:z9.string().min(1)}),NotificationEventSchema=z9.discriminatedUnion("type",[z9.object({type:z9.literal(NOTIFICATION_EVENTS.created),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.stateChanged),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.unreadChanged),payload:NotificationAudienceSchema})])}});import{z as z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";function 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,path54){let conditionPath=[...path54,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,path54)=>{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,path54));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path54,fieldName,variant.uid]);else walk(field.schema.fields,[...path54,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path54,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path54,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=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),group:z11.union([z11.string().min(1),z11.array(z11.string().min(1)).min(1)]).optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="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=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_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_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_provider_errors_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_billing_legacy_premium_enroll","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","env","project","day"]),OpsAgentHealthInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),env:z13.string().trim().min(1).max(64).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsBillingCacheInvalidateInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z13.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z13.object({path:OpsProjectFilePathSchema,content:z13.string().max(256*1024),overwrite:z13.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z13.string().trim().length(64),consentReference:z13.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z13.intersection(OpsProjectOperationPlanInputSchema,z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z14}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z14.object({kind:z14.literal("say"),label:z14.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z14.string().min(1).max(240).optional(),message:z14.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z14.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z14.discriminatedUnion("command",[z14.object({kind:z14.literal("app"),command:z14.literal("publish")}).strict(),z14.object({kind:z14.literal("app"),command:z14.literal("connect"),integrationKey:z14.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z14.object({fallback:z14.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z14.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z14.literal("choices"),text:z14.string().max(500).optional(),actions:z14.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z14.discriminatedUnion("kind",[z14.object({kind:z14.literal("entry"),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("asset"),assetId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("url"),url:z14.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z14.literal("table"),columns:z14.array(z14.object({label:z14.string().min(1).max(24)})).min(2).max(4),rows:z14.array(z14.object({cells:z14.array(z14.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:z14.literal("cards"),layout:z14.enum(["rail","stack"]).optional(),items:z14.array(z14.object({title:z14.string().min(1).max(60),subtitle:z14.string().min(1).max(120).optional(),imageUrl:z14.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z14.literal("entry"),label:z14.string().min(1).max(80),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120),path:z14.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z14.literal("assets"),items:z14.array(z14.object({url:z14.url({protocol:/^https$/}).max(2e3),alt:z14.string().min(1).max(120),label:z14.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z14.literal("callout"),title:z14.string().min(1).max(80),text:z14.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z14.literal("stat"),items:z14.array(z14.object({label:z14.string().min(1).max(24),value:z14.string().min(1).max(16),delta:z14.string().min(1).max(12).optional(),tone:z14.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z14.literal("chart"),unit:z14.string().min(1).max(12).optional(),points:z14.array(z14.object({label:z14.string().min(1).max(12),value:z14.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z14.literal("text"),placeholder:z14.string().min(1).max(120).optional(),multiline:z14.boolean().optional()}).strict(),ChatFormStepIdSchema=z14.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z14.object({id:ChatFormStepIdSchema,token:z14.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z14.string().trim().min(1).max(60),reason:z14.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z14.literal("capabilities"),items:z14.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z14.object({id:ChatFormStepIdSchema.optional(),question:z14.string().min(1).max(500),header:z14.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z14.boolean(),recommended:z14.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."}),step.body.type==="capabilities"&&!step.multiSelect&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}),FormBlockSchema=BlockBaseSchema.extend({type:z14.literal("form"),steps:z14.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z14.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z14.object({stepId:ChatFormStepIdSchema.optional(),header:z14.string().min(1).max(25),question:z14.string().min(1).max(500),answer:z14.string().min(1),selectedLabels:z14.array(z14.string().min(1).max(120)).max(8),freeText:z14.string(),skipped:z14.boolean()}),ChatFormAnswerMetadataSchema=z14.object({toolCallId:z14.string().max(255).optional(),shortTitle:z14.string().max(80).optional(),questions:z14.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z14.string().min(1).max(255)})}});import{z as z15}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z15.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z15.object({dev:z15.string().trim().min(1).optional(),build:z15.string().trim().min(1).optional(),install:z15.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z15.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z15.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z15.object({type:z15.enum(["header","cookie","query","host"]),key:z15.string().min(1).optional(),value:z15.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z15.array(FimoHostingConditionSchema).min(1).optional(),missing:z15.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),permanent:z15.boolean().optional(),statusCode:z15.union([z15.literal(301),z15.literal(302),z15.literal(307),z15.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z15.object({source:z15.string().min(1),headers:z15.array(z15.object({key:z15.string().min(1),value:z15.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z15.object({rewrites:z15.array(FimoHostingRewriteSchema).optional(),redirects:z15.array(FimoHostingRedirectSchema).optional(),headers:z15.array(FimoHostingHeaderSchema).optional(),cleanUrls:z15.boolean().optional(),trailingSlash:z15.boolean().optional()}).strict(),FimoAppConfigSchema=z15.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(path54){return[...path54.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path54){return pageRouteParamNames(path54).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z16}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,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_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=z16.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z16.string(),displayName:z16.string().nullable(),subdomain:z16.string().nullable().optional(),subdomainUpdatedAt:z16.date().nullable().optional(),organizationId:z16.string().nullable(),createdBy:z16.string().nullable(),previewEnabled:z16.boolean().default(!0),enabledChatModels:z16.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z16.string(),thumbnailUrl:z16.string().nullable(),publishedThumbnailUrl:z16.string().nullable(),category:z16.string().nullable(),appUrl:z16.string().nullable(),lastPublishedAt:z16.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z16.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z16.object({id:z16.uuid(),name:z16.string(),displayName:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),category:z16.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z16.object({id:z16.string(),name:z16.string(),avatar:z16.string().nullable(),color:z16.object({bg:z16.string(),text:z16.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z16.object({path:z16.string(),content:z16.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z16.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z16.object({id:z16.string(),messageId:z16.string(),versionId:z16.string().nullable(),role:ProjectChatMessageRole,parts:z16.array(z16.any()),createdAt:z16.coerce.date()}),MessageUserMetadataSchema=z16.object({id:z16.string(),name:z16.string().nullable().optional(),image:z16.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z16.number(),metadata:z16.object({user:MessageUserMetadataSchema,changeManifest:z16.array(z16.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z16.object({versionId:z16.uuid(),commitHash:z16.string(),name:z16.string(),description:z16.string().nullable(),kind:z16.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z16.object({versionCount:z16.number().int().nonnegative(),snapshotBytes:z16.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z16.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z16.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z16.object({content:z16.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z16.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z16.object({success:z16.boolean(),message:z16.string().optional(),warning:z16.string().optional(),durationMs:z16.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z16.object({isPublished:z16.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z16.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z16.object({label:z16.string().trim().min(1).max(120).optional(),notes:z16.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z16.object({success:z16.boolean(),message:z16.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z16.boolean(),publicationId:z16.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z17}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=z17.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z17.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z17.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z17.string().nullable(),deletedAt:z17.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z17.object({id:z17.union([z17.literal(PREVIEW_ENVIRONMENT_KEY),z17.uuid()]),name:z17.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z17.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z17.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z17.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z17.object({surface:z17.enum(["code","schemas","content","translations","assets","forms"]),status:z17.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z17.number().int().nonnegative(),conflictCount:z17.number().int().nonnegative()}),EnvDiffResultSchema=z17.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z17.coerce.date(),surfaces:z17.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z18}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=z18.object({projectId:z18.uuid(),name:z18.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z18.literal("production"),sourceBranch:EnvSchema,isPublished:z18.boolean(),url:z18.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PREVIEW_ENVIRONMENT_KEY),kind:z18.literal("preview"),matchedBranchCount:z18.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z18.literal("custom"),matchedBranchCount:z18.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z18.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z18.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z18.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z18.object({deletedId:z18.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z19}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=z19.object({kind:z19.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z19.object({kind:z19.enum(["variable","secret"]),value:z19.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z19.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z19.object({kind:z19.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),key:z19.string(),kind:z19.literal("secret"),exposure:z19.literal("private"),environment:EnvironmentKeySchema,maskedValue:z19.string().optional(),createdAt:z19.date().transform(value=>value.toISOString()),updatedAt:z19.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z19.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z20}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=z20.object({success:z20.literal(!0),downloadUrl:z20.string(),expiresAt:z20.string(),fileSize:z20.number(),duration:z20.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z20.object({success:z20.literal(!0),projectId:z20.string(),projectName:z20.string(),displayName:z20.string(),projectUrl:z20.string(),duration:z20.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z20.object({contentTypes:z20.number(),entries:z20.number(),assets:z20.number(),translations:z20.number(),forms:z20.number(),codeFiles:z20.number(),assetFiles:z20.number()}),ImportPreviewSurfaceDTOSchema=z20.object({name:z20.string(),included:z20.boolean(),count:z20.number().optional(),note:z20.string().optional()}),ImportPreviewDTOSchema=z20.object({projectName:z20.string(),displayName:z20.string().nullable(),category:z20.string().nullable(),exportedAt:z20.string(),version:z20.string(),envScope:z20.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z20.array(ImportPreviewSurfaceDTOSchema),fileSize:z20.number(),fileName:z20.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z20.object({success:z20.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z21}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=z21.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z21.object({type:z21.literal("manual")}),ScheduleTriggerSchema=z21.object({type:z21.literal("schedule"),cron:z21.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:z21.string().optional()}),WebhookTriggerSchema=z21.object({type:z21.literal("webhook"),path:z21.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z21.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z22}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=z22.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z22.object({token:z22.string().min(1),risk:CapabilityRiskTierSchema,description:z22.string()}),AgentSubAgentSummarySchema=z22.object({name:z22.string().min(1),grant:z22.enum(["inherit","explicit"]),effectiveCaps:z22.array(z22.string().min(1))}),AgentInstallSummaryDTOSchema=z22.object({agentName:z22.string().min(1),env:z22.string().min(1),declaredCapabilities:z22.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z22.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z22.array(CapabilitySummaryEntrySchema),criticalCapabilities:z22.array(CapabilitySummaryEntrySchema),subAgents:z22.array(AgentSubAgentSummarySchema),declaresDelegate:z22.boolean(),cycle:z22.array(z22.string()).nullable(),missingSubAgents:z22.array(z22.string()),warnings:z22.array(z22.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z23}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=z23.object({kind:TriggerKindSchema,summary:z23.string()}),AgentListItemTriggerStateSchema=z23.object({triggerIndex:z23.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z23.boolean(),wired:z23.boolean(),syncError:z23.string().nullable()}),AgentListItemDTOSchema=z23.object({name:z23.string().min(1),description:z23.string().nullable(),goalFirstLine:z23.string().nullable(),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),triggers:z23.array(AgentListItemTriggerSchema),triggerStates:z23.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z23.array(AgentListItemDTOSchema))}});import{z as z24}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=z24.object({args:z24.unknown().optional(),requestId:z24.string().min(1).max(128).optional()}),DispatchSkippedSchema=z24.object({skipped:z24.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z24.object({sessionId:z24.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z24.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z25}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=z25.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z25.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z25.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z25.object({verb:SurfaceDeltaVerbSchema,key:z25.string(),detail:z25.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z25.record(z25.string(),z25.unknown()).optional()}),PerSurfaceDeltaSchema=z25.object({surface:SurfaceNameSchema,status:z25.enum(["ok","timed_out","failed","unchanged"]),durationMs:z25.number().int().nonnegative().optional(),changedCount:z25.number().int().nonnegative(),conflictCount:z25.number().int().nonnegative(),items:z25.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z25.boolean().optional(),error:z25.string().optional()}),CrossSurfaceFindingSchema=z25.object({id:z25.string(),kind:z25.string(),description:z25.string(),severity:z25.enum(["warning","error"]),source:z25.object({surface:SurfaceNameSchema,key:z25.string()}),target:z25.object({surface:SurfaceNameSchema,key:z25.string()}),actions:z25.array(z25.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z25.object({env:EnvSchema,vs:EnvSchema,syncState:z25.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),agents:z25.array(z25.object({id:z25.string(),name:z25.string(),status:z25.enum(["active","paused","failed"]),lastRunAt:z25.coerce.date().nullable()})).optional(),crossSurface:z25.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z25.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),crossSurface:z25.array(CrossSurfaceFindingSchema).optional(),fingerprint:z25.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z25.object({path:z25.string(),state:z25.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z25.string(),additions:z25.number().int().nonnegative(),deletions:z25.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z25.object({oid:z25.string().optional(),content:z25.string().optional(),truncated:z25.boolean(),binary:z25.boolean()}),CodeConflictDetailSchema=z25.object({path:z25.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z25.string(),targetTipSha:z25.string(),mergeBaseSha:z25.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z25.object({id:z25.string(),slug:z25.string(),contentType:z25.string(),data:z25.record(z25.string(),z25.unknown()),updatedAt:z25.coerce.date()}),ContentRowDiffSchema=z25.object({collection:z25.string(),rowId:z25.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z25.object({name:z25.string(),label:z25.string(),isSingleton:z25.boolean(),fields:z25.record(z25.string(),z25.unknown())}),SchemaTypeDiffSchema=z25.object({typeName:z25.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z25.object({id:z25.string(),name:z25.string(),type:z25.enum(["file","folder"]),mimeType:z25.string().nullable(),storageKey:z25.string().nullable(),url:z25.string().nullable(),fileSize:z25.number().nullable(),width:z25.number().nullable(),height:z25.number().nullable(),altText:z25.string().nullable(),caption:z25.string().nullable(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),AssetDiffSchema=z25.object({assetId:z25.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z25.object({locale:z25.string(),key:z25.string(),parent:z25.string().nullable(),child:z25.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z25.object({formName:z25.string(),label:z25.string().nullable(),schemaFingerprint:z25.string(),fields:z25.record(z25.string(),z25.unknown()),settings:z25.record(z25.string(),z25.unknown()).optional()}),FormSchemaDiffSchema=z25.object({formName:z25.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=z25.enum(CONFLICT_KINDS),ConflictSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),kind:ConflictKindSchema.optional(),description:z25.string(),parentValue:z25.unknown().optional(),childValue:z25.unknown().optional(),conflictingFields:z25.array(z25.string()).optional(),code:z25.object({path:z25.string(),unresolvable:z25.boolean().optional(),reason:z25.string().optional()}).optional()}),FieldPickSchema=z25.object({field:z25.string(),choice:z25.enum(["parent","child","pick","ai-pick"]),pickedValue:z25.unknown().optional(),aiSessionId:z25.string().optional()}),ConflictResolutionSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),choice:z25.enum(["parent","child","pick"]),pickedValue:z25.unknown().optional(),fieldPicks:z25.array(FieldPickSchema).optional()}),MergeResultSchema=z25.object({ok:z25.boolean(),mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z25.array(z25.object({surface:SurfaceNameSchema,count:z25.number().int().nonnegative()})),conflicts:z25.array(ConflictSchema).optional(),summary:z25.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z25.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z25.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z25.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z25.boolean().optional()}),ResolvedStrategySchema=z25.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z25.boolean()}),MergeRequestSchema=z25.object({from:EnvSchema,allowDirectMerge:z25.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z25.object({mergeId:z25.string().uuid(),streamUrl:z25.string(),strategy:ResolvedStrategySchema,acceptedAt:z25.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z25.object({mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z25.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z25.array(ConflictSchema),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedBy:z25.string().nullable(),lastEditedAt:z25.coerce.date().nullable(),initiator:z25.object({userId:z25.string().nullable(),role:z25.string().nullable(),agentName:z25.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z25.object({resolutions:z25.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z25.object({mergeId:z25.string().uuid(),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedAt:z25.coerce.date(),lastEditedBy:z25.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z25.object({mergeId:z25.string().uuid(),resolutions:z25.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z25.object({mergeId:z25.string().uuid()}),PublishReleaseRequestSchema=z25.object({version:z25.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z25.string().max(2e4).optional()}),PublishReleaseResultSchema=z25.object({releaseTag:z25.string(),sha:z25.string(),publishedAt:z25.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z26}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=z26.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z26.object({cpuMs:z26.number().nonnegative().default(0),netBytes:z26.number().nonnegative().default(0),walltimeMs:z26.number().nonnegative().default(0),llmTokensIn:z26.number().nonnegative().optional(),llmTokensOut:z26.number().nonnegative().optional(),stepCount:z26.number().int().nonnegative().optional(),toolCallCounts:z26.record(z26.string().min(1).max(120),z26.number().int().nonnegative()).optional(),toolCallOutcomes:z26.array(z26.object({toolName:z26.string().min(1).max(120),success:z26.boolean(),code:z26.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z26.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z26.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z26.object({capturedAt:z26.coerce.date(),fingerprint:z26.string().min(1).max(256),counts:z26.object({code:z26.number().int().nonnegative(),content:z26.number().int().nonnegative(),schemas:z26.number().int().nonnegative(),labels:z26.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z26.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z26.object({diff:DiffReportSchema,code:z26.array(CodeFileDiffSchema.extend({raw:z26.string().max(24576)})).max(200),schemas:z26.array(SchemaTypeDiffSchema).max(200),content:z26.array(z26.object({key:z26.string().min(1).max(512),collection:z26.string().min(1).max(256),slug:z26.string().max(512).optional(),verb:z26.enum(["added","modified","deleted"]),fields:z26.array(z26.object({name:z26.string().min(1).max(256),before:z26.unknown().optional(),after:z26.unknown().optional()})).max(20)})).max(200),labels:z26.array(z26.object({key:z26.string().min(1).max(512),locale:z26.string().min(1).max(64).optional(),before:z26.unknown().nullable(),after:z26.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),env:EnvSchema,agentName:z26.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z26.unknown().optional(),capabilities:z26.array(z26.string()).optional(),dataSources:z26.array(z26.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z26.string().nullable(),startedAt:z26.coerce.date().nullable(),finishedAt:z26.coerce.date().nullable(),cancelledAt:z26.coerce.date().nullable(),costUsd:z26.number().nonnegative(),costCeilingUsd:z26.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z26.boolean(),lastCheckpointId:z26.uuid().nullable(),branchEnvId:z26.uuid().nullable(),parentSessionId:z26.uuid().nullable(),terminalReason:z26.string().nullable(),errorMessage:z26.string().nullable(),report:z26.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z26.object({id:z26.uuid(),sessionId:z26.uuid(),checkpointIdx:z26.number().int().nonnegative(),payloadRef:z26.string(),payloadSizeBytes:z26.number().int().nonnegative(),checksum:z26.string().length(64),createdAt:z26.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z26.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z26.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z26.object({session:AgentSessionDTOSchema,checkpoints:z26.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z26.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","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z26.object({reason:z26.string().min(1).max(120).optional()})}});import{z as z27}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=z27.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z27.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z27.object({id:z27.uuid(),envId:z27.uuid(),sessionId:z27.uuid().nullable(),skillName:z27.string().min(1),classification:AgentBranchClassificationSchema,rationale:z27.string().nullable(),summary:z27.string().nullable(),surfaceDeltas:z27.record(z27.string(),z27.unknown()),createdAt:z27.coerce.date(),decidedAt:z27.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z27.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z27.object({path:z27.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z27.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z27.object({code:z27.literal("merge_conflict"),message:z27.string(),conflicts:z27.record(z27.string(),z27.number().int().nonnegative())})}});import{z as z28}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z28.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z28.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z28.object({description:z28.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z28.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z28.object({id:z28.uuid(),projectId:z28.uuid(),threadId:z28.uuid(),invocationId:z28.uuid(),agentKey:z28.string().min(1).max(120),anchorEnv:z28.string().min(1).max(64),retainedEnv:z28.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z28.string().min(1).nullable(),continuationInvocationId:z28.uuid().nullable(),askedAt:z28.coerce.date(),expiresAt:z28.coerce.date(),closedAt:z28.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z28.object({questionId:z28.uuid(),invocationId:z28.uuid(),askedAt:z28.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z28.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z28.object({question:AgentQuestionSchema,continuationInvocationId:z28.uuid(),deduped:z28.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z29}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,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z29.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z29.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z29.enum(["secret_text"]),IntegrationCredentialUsageSchema=z29.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z29.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z29.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z29.object({mode:IntegrationAuthModeSchema,label:z29.string().min(1),description:z29.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z29.object({id:z29.string().min(1),label:z29.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z29.boolean()}),IntegrationToolDefinitionDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),description:z29.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z29.object({title:z29.string().min(1),description:z29.string().min(1),command:z29.string().min(1).optional()}),IntegrationInfoDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),type:z29.enum(["native","mcp"]).optional(),url:z29.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z29.array(IntegrationAuthModeDTOSchema),credentials:z29.array(IntegrationCredentialDefinitionDTOSchema),tools:z29.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z29.enum(["available","unavailable"]).optional(),recipes:z29.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),installed:z29.boolean(),enabled:z29.boolean(),setupState:z29.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z29.string().nullable(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),connectionStatus:z29.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),installedAt:z29.coerce.date().nullable(),updatedAt:z29.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),enabled:z29.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z29.string(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z29.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z29.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z29.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z29.object({value:z29.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z29.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z29.object({id:z29.uuid(),organizationId:z29.string().min(1),integrationKey:z29.string().min(1),alias:z29.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z29.string().min(1),externalAccountName:z29.string().nullable(),externalBotUserId:z29.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z29.array(z29.string()),connectedAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z29.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z29.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z29.record(McpHeaderNameSchema,z29.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z29.object({alias:z29.string().min(1).max(120).optional(),token:z29.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z29.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z29.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),alias:z29.string().min(1).max(120),token:z29.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z29.boolean().optional()}),z29.object({mode:z29.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z29.boolean().optional()})]).superRefine((value,ctx)=>{value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z29.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z29.union([z29.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z29.object({type:z29.literal("mcp"),name:z29.string().trim().min(1).max(120),url:z29.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z29.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z29.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z29.object({integrationKey:z29.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z29.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z29.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z29.literal("oauth"),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()})]),ReusableMcpServerAuthKindSchema=z29.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z29.object({id:z29.uuid(),name:z29.string().min(1),host:z29.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z29.string().min(1),availability:z29.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z29.object({query:z29.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z29.object({serverId:z29.uuid()}),StartProjectIntegrationConnectResponseSchema=z29.object({integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),integrationKey:z29.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z29.object({mode:z29.literal("oauth"),integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()})]),BindProjectChannelRequestSchema=z29.object({ref:z29.string().min(1),connectionAlias:z29.string().min(1).optional(),agentName:z29.string().min(1).max(160).nullable().optional(),force:z29.boolean().optional()}),ListProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1)}),SearchProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1),connectionAlias:z29.string().min(1),query:z29.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),connectionId:z29.uuid(),externalWorkspaceId:z29.string().min(1),externalChannelId:z29.string().min(1),externalChannelName:z29.string().nullable(),agentName:z29.string().nullable(),enabled:z29.boolean(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z29.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z29.object({id:z29.string().min(1),name:z29.string().min(1),visibility:z29.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z29.string().min(1).nullable(),canMove:z29.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z29.object({markdown:z29.boolean().optional(),summary:z29.boolean().optional(),links:z29.boolean().optional(),branding:z29.boolean().optional(),images:z29.boolean().optional(),html:z29.union([z29.literal("cleaned"),z29.literal("raw"),z29.boolean()]).optional(),json:z29.union([z29.boolean(),z29.object({prompt:z29.string().min(1).max(1e4),schema:z29.record(z29.string(),z29.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z29.object({url:z29.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z29.object({query:z29.string().min(1),maxResults:z29.number().int().positive().max(20).optional(),sources:z29.array(z29.enum(["web","news","images"])).min(1).max(3).optional(),categories:z29.array(z29.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z29.enum(["hour","day","week","month","year"]).optional(),location:z29.string().min(1).max(160).optional(),country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(100).optional(),types:z29.array(z29.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),sources:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),passages:z29.number().int().min(1).max(5).optional(),skills:z29.literal("only").optional(),language:z29.string().min(1).optional(),topic:z29.string().min(1).optional(),license:z29.string().min(1).optional(),minStars:z29.number().int().min(0).optional(),maxStars:z29.number().int().min(0).optional(),archived:z29.boolean().optional(),fork:z29.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(500).optional(),authors:z29.array(z29.string().min(1)).min(1).optional(),categories:z29.array(z29.string().min(1)).min(1).optional(),from:z29.iso.date().optional(),to:z29.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),query:z29.string().min(1).max(500).optional(),maxPassages:z29.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),intent:z29.string().min(1).max(500),mode:z29.enum(["similar","citers","references"]).optional(),maxResults:z29.number().int().min(1).max(500).optional(),rerank:z29.boolean().optional(),anchors:z29.array(z29.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z29.object({url:z29.string().url(),search:z29.string().min(1).optional(),limit:z29.number().int().positive().max(200).optional(),includeSubdomains:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z29.object({url:z29.string().url(),limit:z29.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z29.object({text:z29.string().min(1).max(200).optional(),cron:z29.string().min(1).max(120).optional(),timezone:z29.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z29.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z29.union([z29.object({type:z29.enum(["scrape","crawl"]).default("scrape"),urls:z29.array(z29.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z29.object({type:z29.literal("search"),queries:z29.array(z29.string().min(1).max(256)).min(1).max(12),searchWindow:z29.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z29.number().int().min(1).max(50).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z29.object({name:z29.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),notification:z29.object({email:z29.object({enabled:z29.boolean().default(!0),recipients:z29.array(z29.string().email()).min(1).max(20),includeDiffs:z29.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z29.object({monitorId:z29.string().uuid(),name:z29.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),status:z29.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z29.object({monitorId:z29.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z29.string().uuid()}),RunProjectIntegrationToolRequestSchema=z29.object({tool:z29.string().min(1),input:z29.record(z29.string(),z29.unknown()),connectionAlias:z29.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z29.object({provider:z29.string().min(1),providerCredits:z29.number().nonnegative().optional(),providerCostUsd:z29.number().nonnegative().optional(),requests:z29.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z29.object({credits:z29.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),json:z29.unknown().optional(),branding:z29.record(z29.string(),z29.unknown()).optional(),warning:z29.string().optional()}),FirecrawlSearchToolOutputSchema=z29.object({query:z29.string(),provider:z29.literal("firecrawl"),warning:z29.string().optional(),results:z29.array(z29.object({title:z29.string(),url:z29.string(),snippet:z29.string().optional(),content:z29.string().optional(),score:z29.number().optional(),publishedAt:z29.string().optional()}))}),FirecrawlResearchPaperSchema=z29.object({paperId:z29.string(),primaryId:z29.string().optional(),ids:z29.record(z29.string(),z29.array(z29.string())).optional(),title:z29.string().optional(),abstract:z29.string().optional(),score:z29.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z29.object({text:z29.string(),score:z29.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(z29.object({id:z29.string(),type:z29.string().min(1).optional(),url:z29.string(),title:z29.string().optional(),passages:z29.array(z29.object({text:z29.string()}).passthrough())}).passthrough()),coverage:z29.record(z29.string(),z29.string()).optional(),reranked:z29.boolean().optional(),repos:z29.array(z29.record(z29.string(),z29.unknown())).optional(),sources:z29.array(z29.record(z29.string(),z29.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),paper:z29.record(z29.string(),z29.unknown()),paperId:z29.string().optional(),query:z29.string().optional(),passages:z29.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema),poolSize:z29.number().int().nonnegative(),truncated:z29.boolean(),note:z29.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),count:z29.number(),links:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),description:z29.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),total:z29.number(),pages:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),warning:z29.string().optional()})),warning:z29.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z29.object({cron:z29.string().optional(),text:z29.string().optional(),timezone:z29.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z29.object({id:z29.string().optional(),type:z29.enum(["scrape","crawl","search"]).optional(),urls:z29.array(z29.string()).optional(),queries:z29.array(z29.string()).optional(),searchWindow:z29.string().optional(),maxResults:z29.number().optional(),includeDomains:z29.array(z29.string()).optional(),excludeDomains:z29.array(z29.string()).optional(),scrapeOptions:z29.record(z29.string(),z29.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z29.object({id:z29.string(),name:z29.string(),status:z29.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z29.string().nullable().optional(),lastRunAt:z29.string().nullable().optional(),currentCheckId:z29.string().nullable().optional(),targets:z29.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z29.string().nullable().optional(),judgeEnabled:z29.boolean().optional(),estimatedCreditsPerMonth:z29.number().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z29.object({id:z29.string(),monitorId:z29.string(),scheduledFor:z29.string().nullable().optional(),startedAt:z29.string().nullable().optional(),finishedAt:z29.string().nullable().optional(),estimatedCredits:z29.number().optional(),reservedCredits:z29.number().optional(),actualCredits:z29.number().optional(),billingStatus:z29.string().nullable().optional(),summary:z29.object({totalPages:z29.number().optional(),same:z29.number().optional(),changed:z29.number().optional(),new:z29.number().optional(),removed:z29.number().optional(),error:z29.number().optional()}).passthrough().optional(),error:z29.string().nullable().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitors:z29.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),deleted:z29.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),checks:z29.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),check:FirecrawlMonitorCheckOutputSchema,next:z29.string().optional()}),FirecrawlToolKeySchema=z29.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z29.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),tool:z29.string().min(1),connectionAlias:z29.string().min(1).nullable().optional(),output:z29.record(z29.string(),z29.unknown()),executedAt:z29.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z29.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z29.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z29.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z29.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z29.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z29.array(ProjectChannelCandidateDTOSchema))}});import{z as z30}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=z30.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z30.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z30.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z30.object({userId:z30.string().min(1),name:z30.string(),email:z30.string().min(1),subscribed:z30.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z30.object({maxSubscribers:z30.number().int().positive(),subscriberCount:z30.number().int().nonnegative(),effectiveRecipientCount:z30.number().int().nonnegative(),currentUserSubscribed:z30.boolean(),candidates:z30.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z30.object({userIds:z30.array(z30.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z30.object({topic:UserManagedNotificationTopicSchema,enabled:z30.boolean(),source:z30.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z30.object({topics:z30.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z30.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z30.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z30.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z30.string().nullable(),maskedEmail:z30.string().min(1),applied:z30.boolean(),expiresAt:z30.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z30.object({scheduleId:z30.string().min(1),scheduleName:z30.string(),projectId:z30.string().min(1),projectName:z30.string(),env:z30.string().min(1)}),FollowedSchedulesSchema=z30.object({schedules:z30.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z31}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=z31.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=z31.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z31.uuid(),env:z31.string().min(1),name:z31.string().min(1),cron:z31.string().min(1),command:z31.string().min(1),secretKeys:z31.array(z31.string().min(1)),enabled:z31.boolean(),lastRunAt:z31.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z31.string().nullable(),overPolicyReasons:z31.array(z31.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120),cron:z31.string().min(1).max(120),command:z31.string().min(1).max(500),secretKeys:z31.array(ProjectSecretKeySchema).default([]),enabled:z31.boolean().optional()}),UpdateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120).optional(),cron:z31.string().min(1).max(120).optional(),command:z31.string().min(1).max(500).optional(),secretKeys:z31.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z31.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z31.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z31.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z31.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z31.object({maxRuns:z31.number().int().positive(),retentionDays:z31.number().int().positive().nullable(),outputRetentionDays:z31.number().int().positive(),maxOutputBytes:z31.number().int().positive()}),SchedulePolicyStateSchema=z31.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z31.object({code:z31.enum(["Free","Premium","Pro"]),source:z31.enum(["cached_subscription","free_fallback"]),activeSchedules:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),concurrency:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),compute:z31.object({settledMs:z31.number().int().nonnegative(),reservedMs:z31.number().int().nonnegative(),includedMs:z31.number().int().positive(),remainingMs:z31.number().int().nonnegative(),resetsAt:z31.coerce.date()}),upgrade:z31.object({code:z31.literal("Pro"),activeSchedulesLimit:z31.number().int().positive(),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),maxConcurrentRuns:z31.number().int().positive(),computeIncludedMs:z31.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z31.array(z31.string())}),ProjectScheduleUsageSchema=z31.object({runCount:z31.number().int().nonnegative(),runsWithOutput:z31.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z31.object({id:z31.uuid(),scheduleId:z31.uuid(),projectId:z31.uuid(),env:z31.string().min(1),scheduleName:z31.string().min(1),command:z31.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z31.object({id:z31.string().min(1),name:z31.string().min(1)}).nullable(),queuedAt:z31.coerce.date(),startedAt:z31.coerce.date().nullable(),finishedAt:z31.coerce.date().nullable(),exitCode:z31.number().int().nullable(),errorCode:z31.string().nullable(),error:z31.string().nullable(),outputBytes:z31.number().int().nonnegative(),outputTruncated:z31.boolean(),outputExpiresAt:z31.coerce.date().nullable(),metadataExpiresAt:z31.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z31.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z31.coerce.date().nullable(),items:z31.array(z31.object({key:z31.string().min(1),updatedAt:z31.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z31.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z31.object({trigger:z31.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z31.object({limit:z31.coerce.number().int().min(1).max(100).default(25),cursor:z31.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z31.object({items:z31.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z31.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z31.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z31.object({items:z31.array(ProjectScheduleRunDTOSchema),nextCursor:z31.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z32}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,WorkNotificationPreferencesSchema,WorkNotificationPreferencesResponseSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z32.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z32.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z32.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("user"),userId:z32.string().min(1)}).strict(),z32.object({kind:z32.literal("agent"),agentKey:z32.string().min(1).max(120),agentId:z32.uuid().optional()}).strict(),z32.object({kind:z32.literal("system")}).strict()]),NotificationSummarySchema=z32.string().trim().min(1).max(1200),NotificationRunOutcomeSchema=z32.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z32.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z32.discriminatedUnion("topic",[z32.object({topic:z32.literal("agent_question"),questionId:z32.uuid(),title:z32.string().trim().min(1).max(80),description:z32.string().trim().min(1).max(240)}).strict(),z32.object({topic:z32.literal("agent_run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().optional(),proposalId:z32.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().optional(),summary:NotificationSummarySchema.optional()}).strict()]),NotificationEnvelopeSchema=z32.object({id:z32.uuid(),projectId:z32.uuid(),sourceKey:z32.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z32.literal(1),payload:NotificationPayloadSchema,createdAt:z32.coerce.date()}),NotificationRecipientStateSchema=z32.object({id:z32.uuid(),notificationId:z32.uuid(),projectId:z32.uuid(),userId:z32.string().min(1),readAt:z32.coerce.date().nullable(),archivedAt:z32.coerce.date().nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationDeliveryStateSchema=z32.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z32.object({id:z32.uuid(),notificationRecipientId:z32.uuid(),projectId:z32.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z32.number().int().nonnegative(),nextAttemptAt:z32.coerce.date().nullable(),lastAttemptAt:z32.coerce.date().nullable(),sentAt:z32.coerce.date().nullable(),failureCode:z32.string().max(80).nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationPreferenceSchema=z32.object({topic:WorkNotificationTopicSchema,channel:z32.literal("email"),enabled:z32.boolean(),source:z32.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z32.object({topics:z32.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("question"),questionId:z32.uuid()}).strict(),z32.object({kind:z32.literal("run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z32.object({kind:z32.literal("retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().nullable(),proposalId:z32.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z32.object({kind:z32.literal("merge_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().nullable()}).strict()]),NotificationViewSchema=z32.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z32.object({items:z32.array(NotificationViewSchema),nextCursor:z32.string().nullable(),unreadCount:z32.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z32.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z32.string().min(1).max(120).optional(),sourceKey:z32.string().min(1).max(255).optional(),unread:z32.stringbool().optional(),archived:z32.stringbool().optional(),limit:z32.coerce.number().int().min(1).max(100).optional(),cursor:z32.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z32.object({recipient:NotificationRecipientStateSchema,unreadCount:z32.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z32.object({read:z32.boolean().optional(),archived:z32.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z33}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=z33.object({id:z33.uuid(),occurredAt:z33.coerce.date(),projectId:z33.uuid().nullable(),env:z33.string().nullable(),actor:z33.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z33.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z33.unknown().optional(),ipAddress:z33.string().nullable().optional(),userAgent:z33.string().nullable().optional(),error:z33.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z33.object({rows:z33.array(AuditLogRowDTOSchema),nextCursor:z33.string().nullable()})),AuditLogQuerySchema=z33.object({env:z33.string().optional(),action:AuditActionSchema.optional(),actor:z33.string().optional(),from:z33.coerce.date().optional(),to:z33.coerce.date().optional(),limit:z33.coerce.number().int().min(1).max(200).optional(),cursor:z33.string().optional()})}});import{z as z34}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=z34.object({surface:SurfaceNameSchema,key:z34.string(),label:z34.string()}),InlineSchema=z34.object({text:z34.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z34.discriminatedUnion("type",[z34.object({type:z34.literal("paragraph"),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("preview"),ref:DiffRefSchema,caption:z34.string().optional()}),z34.object({type:z34.literal("code"),code:z34.string(),lang:z34.string().optional(),caption:z34.string().optional()}),z34.object({type:z34.literal("risk"),level:z34.enum(["warning","error"]),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("list"),items:z34.array(z34.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z34.object({headline:z34.string(),blocks:z34.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z34.object({summary:EnvDiffSummarySchema,fingerprint:z34.string(),generatedAt:z34.coerce.date(),cached:z34.boolean().optional(),credits:z34.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z35}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=z35.object({date:z35.string(),visitors:z35.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z35.object({key:z35.string(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z35.object({path:z35.string(),pageName:z35.string().nullable().optional(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z35.object({preset:z35.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z35.string(),requestedTo:z35.string(),effectiveFrom:z35.string(),effectiveTo:z35.string(),isRetentionLimited:z35.boolean(),groupBy:z35.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z35.object({date:z35.string(),content:z35.string(),updatedAt:z35.string(),updatedByUserId:z35.string()}),ProjectPageviewAnalyticsDTOSchema=z35.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative(),bounceRate:z35.number().min(0).max(100),viewsPerVisit:z35.number().nonnegative(),averageVisitDurationSeconds:z35.number().nonnegative(),visitorsSeries:z35.array(ProjectDailyVisitorsDTOSchema),topPages:z35.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z35.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z36}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=z36.object({id:z36.string(),email:z36.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z36.coerce.date(),createdAt:z36.coerce.date(),inviterUserId:z36.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z36.object({id:z36.string(),token:z36.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z36.object({success:z36.boolean(),projectId:z36.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z37}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=z37.object({id:z37.string(),name:z37.string(),image:z37.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z37.object({count:z37.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z37.object({counts:z37.object({signed_up:z37.int(),activated:z37.int()}),credits:z37.object({total:z37.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z37.email(),emailVerified:z37.boolean(),createdAt:z37.coerce.date(),updatedAt:z37.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z38}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=z38.object({id:z38.string(),principalType:ProjectPrincipalTypeSchema,principalId:z38.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z38.coerce.date(),expiresAt:z38.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=z38.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z38.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z38.record(z38.string(),z38.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z38.object({access:z38.array(ProjectAccessItemDTOSchema),invites:z38.array(ProjectInviteDTOSchema),organization:z38.object({name:z38.string().nullable(),logo:z38.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z38.object({success:z38.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z38.object({success:z38.boolean(),projectId:z38.uuid()}))}});import{z as z39}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=z39.object({publicationStatus:PublicationStatusSchema,appUrl:z39.string().nullable(),lastPublishedAt:z39.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z40}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z40.object({url:z40.url(),expiresAt:z40.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z40.object({name:z40.string().min(1),locator:z40.string().min(1).optional(),source:z40.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z40.object({kind:z40.literal("dependency_build_scripts_blocked"),packageManager:z40.enum(["pnpm","yarn","bun"]),packages:z40.array(z40.string()),targets:z40.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z40.string(),approvalKey:z40.string(),command:z40.string().optional(),approval:z40.object({id:z40.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z40.object({code:z40.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z40.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z40.object({approvalId:z40.uuid()}),PreviewInstallPolicyApprovalEventSchema=z40.discriminatedUnion("type",[z40.object({type:z40.literal("progress"),step:z40.enum(["approval","install","restart","readiness"]),message:z40.string()}),z40.object({type:z40.literal("approved")}),z40.object({type:z40.literal("complete")}),z40.object({type:z40.literal("error"),code:z40.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z40.string()})])}});import{z as z41}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:z41.string(),slug:z41.string().nullable(),logo:z41.string().nullable(),metadata:z41.record(z41.string(),z41.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z41.object({id:z41.string(),name:z41.string(),email:z41.email(),image:z41.string().nullable()}),OrganizationMemberDTOSchema=z41.object({id:z41.string(),userId:z41.string(),organizationId:z41.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z41.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z42}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z42.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z42.object({reason:CancellationReasonCodeSchema,details:z42.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z42.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z42.object({offerVersion:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),renewsOn:z42.string()}),PlanMigrationPreviewDTOSchema=z42.object({currency:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),startsAt:z42.string(),renewsAt:z42.string(),nextRenewalAmount:z42.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z42.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z42.object({id:z42.string(),organizationId:z42.string(),legacySubscriptionId:z42.string(),offeredPlanCode:z42.string(),offeredPlanName:z42.string(),offeredPriceAmount:z42.number(),offeredCurrency:z42.string(),offerVersion:z42.string(),state:PlanMigrationStateSchema,checkoutToken:z42.string().nullable(),deadlineAt:z42.string(),transitions:z42.array(z42.object({event:z42.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z42.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z42.object({included:z42.number().optional(),unitPrice:z42.number().optional(),dailyCap:z42.number().nullable().optional()}),EntitlementsDTOSchema=z42.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z42.object({retentionDays:z42.number().int().positive(),canUseExtendedDateRanges:z42.boolean()}).optional(),history:z42.object({retentionDays:z42.number().int().positive()}).optional(),members:z42.object({canInvite:z42.boolean(),maxMembers:z42.number().int().positive().nullable()}).optional(),domains:z42.object({canUseCustomDomains:z42.boolean(),maxDomains:z42.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z42.object({id:z42.string(),external_id:z42.string(),customerId:z42.string(),planId:z42.string(),planCode:z42.union([TemplateCodeSchema,z42.literal("Unknown")]),currentPeriod:z42.object({start:z42.string(),end:z42.string().nullable()}),cancelAt:z42.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z42.string(),nextPaymentAt:z42.string().nullable(),baseAmount:z42.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z42.object({totalCap:z42.number(),dailyCap:z42.number(),usedTotal:z42.number()}),CreditBalanceDTOSchema=z42.object({total:z42.number(),base:z42.number(),dailyBase:z42.number(),purchases:z42.number(),awards:z42.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z42.object({total:z42.number(),nearLimit:z42.boolean(),canChat:z42.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z42.object({dailyFreeAvailable:z42.number(),monthlyAvailable:z42.number(),purchasedAvailable:z42.number(),awardedAvailable:z42.number()}),ProjectDailyCreditAllowanceDTOSchema=z42.object({periodCap:z42.number(),dailyGrant:z42.number(),usedThisPeriod:z42.number(),remainingThisPeriod:z42.number()}),ProjectCreditBalanceDTOSchema=z42.object({projectId:z42.uuid(),organizationId:z42.string(),balance:z42.object({totalAvailable:z42.number(),nearLimit:z42.boolean(),canUseAi:z42.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z42.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z42.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z42.object({planCode:z42.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z42.object({source:z42.enum(["cached_subscription","free_fallback"]),settledMs:z42.number().int().nonnegative(),reservedMs:z42.number().int().nonnegative(),includedMs:z42.number().int().positive(),remainingMs:z42.number().int().nonnegative(),resetsAt:z42.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().nonnegative(),refillAmountUsd:z42.number().nonnegative()}),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().nonnegative().nullable(),refillAmountUsd:z42.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().min(.01).multipleOf(.01),refillAmountUsd:z42.number().min(.01).multipleOf(.01)}).strict(),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z42.object({invoiceId:z42.string(),newBalance:z42.int(),creditCount:z42.int(),amountUsd:z42.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z42.object({url:z42.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 z43}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=z43.object({brand:z43.string(),last4:z43.string(),exp:z43.string(),isDefault:z43.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z44}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,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=z44.string().superRefine((path54,ctx)=>{let segments=path54.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=z44.object({type:z44.literal("renameField"),contentType:z44.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z44.object({enabled:z44.boolean()}).strict(),ContentFieldGroupSchema=z44.object({id:z44.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z44.string().min(1).max(255),default:z44.boolean().optional()}).strict(),ContentTypeDTOSchema=z44.object({id:z44.string(),name:z44.string(),label:z44.string(),isSingleton:z44.boolean(),i18n:ContentTypeI18nSchema,groups:z44.array(ContentFieldGroupSchema).default([]),fields:z44.record(z44.string(),FieldDefinitionSchema),createdAt:z44.string(),updatedAt:z44.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z44.object({contentTypes:z44.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z44.object({id:z44.string(),entryId:z44.string(),documentId:z44.string(),slug:z44.string(),locale:z44.string().optional(),createdAt:z44.string(),updatedAt:z44.string(),__fimo:z44.object({contentType:z44.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({limit:z44.number(),offset:z44.number(),total:z44.number(),hasMore:z44.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z44.object({contentType:z44.string(),count:z44.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z44.object({counts:z44.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z44.object({count:z44.number().int().nonnegative(),sourceLocale:z44.string(),targetLocale:z44.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z44.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z44.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z44.union([z44.string(),z44.number(),z44.boolean(),z44.null()]),entryWhereOperatorSchema=z44.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z44.array(entryWhereScalarSchema).optional(),$nin:z44.array(entryWhereScalarSchema).optional(),$contains:z44.string().optional(),$startsWith:z44.string().optional(),$null:z44.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z44.object({data:z44.record(z44.string(),z44.unknown()),locale:z44.string().min(1).optional(),documentId:z44.uuid().optional()}),entryIdsSchema=z44.array(z44.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z44.object({sql:z44.string().min(1)}),BulkCreateEntriesRequestSchema=z44.object({entries:z44.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z44.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z44.object({updates:z44.array(z44.object({id:z44.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,locale:z44.string().min(1).optional()}),z44.object({where:EntryWhereSchema,locale:z44.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z44.object({data:z44.array(z44.record(z44.string(),z44.unknown())),meta:z44.object({rowCount:z44.number().int().nonnegative(),truncated:z44.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({created:z44.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({updated:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({deleted:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z45}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z45.object({index:z45.number().int().nonnegative(),contentType:z45.string(),field:z45.string(),value:z45.string(),against:z45.enum(["stored","batch"]),ownerDocumentId:z45.uuid().optional(),ownerIndex:z45.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z45.object({code:z45.literal("unique_conflict"),message:z45.string(),conflicts:z45.array(UniqueConflictSchema),truncated:z45.boolean().optional()})}});import{z as z46}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=z46.object({kind:z46.literal("unique_conflict"),contentType:z46.string(),field:z46.string(),value:z46.string(),documentCount:z46.number().int().positive(),documentIds:z46.array(z46.uuid()),documentIdsTruncated:z46.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z46.object({code:z46.literal("schema_transition_rejected"),message:z46.string(),issues:z46.array(SchemaTransitionIssueSchema),truncated:z46.boolean().optional()})}});import{z as z47}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=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z47.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z47.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z47.object({field:CmsFieldNameSchema,direction:z47.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z47.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z47.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z47.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z47.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z47.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z48}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=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema))}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}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=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}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=z51.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z51.object({items:z51.array(ProjectMessagePublicDTOSchema),nextCursor:z51.string().nullable()}),ChatLiveTurnDTOSchema=z51.object({invocationId:z51.string(),step:z51.enum(["preparing","working","compacting","merging"]),startedAt:z51.string()}),ChatLiveTurnStateDTOSchema=z51.object({threadId:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z51.object({id:z51.string(),role:z51.enum(["user","assistant"]),parts:z51.array(z51.unknown()),metadata:z51.record(z51.string(),z51.unknown()).nullable(),versionId:z51.string().nullable().optional(),createdAt:z51.date().transform(value=>value.toISOString()),providerMessageId:z51.string().nullable().optional(),invocationId:z51.string().nullable().optional(),invocationStatus:z51.string().nullable().optional(),invocationTerminalReason:z51.string().nullable().optional()}),ChatAttentionDTOSchema=z51.object({type:z51.literal("merge_conflict"),merge:z51.object({mergeId:z51.string().uuid(),projectId:z51.string(),fromEnv:z51.string(),toEnv:z51.string()}),publishAfterMerge:z51.boolean()}),ChatThreadMessagesPageDTOSchema=z51.object({threadId:z51.string().nullable(),title:z51.string().nullable(),messages:z51.array(ChatThreadMessageDTOSchema),nextCursor:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z51.object({kind:z51.literal("replay"),threadId:z51.string(),userMessageId:z51.string()}),ChatQueuedOutcomeDTOSchema=z51.object({kind:z51.literal("queued"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string()}),ChatBusyOutcomeDTOSchema=z51.object({kind:z51.literal("busy"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string().optional()}),ChatRefusedOutcomeDTOSchema=z51.object({kind:z51.literal("refused"),threadId:z51.string(),userMessageId:z51.string(),refusedInvocationId:z51.string(),terminalReason:z51.string()}),ChatNonStreamingOutcomeDTOSchema=z51.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z51.object({success:z51.boolean(),deletedCount:z51.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z51.object({code:z51.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z51.string()})}});import{z as z52}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=z52.object({url:z52.string().url(),key:z52.string(),size:z52.number(),contentType:z52.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z53}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=z53.object({canAccess:z53.boolean(),permissions:z53.record(z53.string(),z53.boolean()),role:z53.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z54}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:z54.string().trim().default(""),sort:z54.enum(["recent","name","relevance"]).default("recent"),category:z54.string().optional()})}});import{z as z55}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=z55.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z55.enum(["fimo","external"]),PaymentStatusSchema=z55.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z55.object({id:z55.string().uuid(),domain:z55.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z55.boolean(),price:z55.number().int().nullable(),renewalPrice:z55.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z55.string().nullable(),failureReason:z55.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z55.object({domain:z55.string(),available:z55.boolean(),premium:z55.boolean(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),purchaseType:z55.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z55.object({domain:z55.string(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),premium:z55.boolean(),allowedYears:z55.array(z55.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z55.object({firstName:z55.string().max(100),lastName:z55.string().max(100),companyName:z55.string().max(100).optional(),address1:z55.string().max(255),address2:z55.string().max(255).optional(),city:z55.string().max(100),state:z55.string().max(100),zip:z55.string().max(20),country:z55.string().max(2),phone:z55.string().max(30),email:z55.union([z55.string().email().max(255),z55.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z55.object({firstName:z55.string().min(1).max(100),lastName:z55.string().min(1).max(100),companyName:z55.string().max(100).optional(),address1:z55.string().min(1).max(255),address2:z55.string().max(255).optional(),city:z55.string().min(1).max(100),state:z55.string().min(1).max(100),zip:z55.string().min(1).max(20),country:z55.string().min(1).max(2),phone:z55.string().min(1).max(30),email:z55.string().email().max(255)}),SearchDomainsRequestSchema=z55.object({keyword:z55.string().min(1).max(100),tldFilter:z55.array(z55.string()).optional()}),CheckAvailabilityRequestSchema=z55.object({domains:z55.array(z55.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=z55.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z55.object({domain:DomainNameSchema,years:z55.number().int().min(1).max(10).optional().default(3),autoRenew:z55.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z55.object({autoRenew:z55.boolean().optional()}),RenewDomainRequestSchema=z55.object({years:z55.number().int().min(1).max(10).optional().default(1),autoRenew:z55.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z55.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z55.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z55.object({verified:z55.boolean(),email:z55.string().nullable(),verifyBy:z55.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z56}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=z56.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=z56.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=z56.object({txtName:z56.string().nullable().optional(),txtValue:z56.string().nullable().optional(),httpUrl:z56.string().nullable().optional(),httpBody:z56.string().nullable().optional(),cname:z56.string().nullable().optional(),cnameTarget:z56.string().nullable().optional()}),SSLValidationErrorSchema=z56.object({message:z56.string()}),OwnershipVerificationSchema=z56.object({type:z56.string(),name:z56.string(),value:z56.string()}),ProjectDomainSSLDTOSchema=z56.object({status:z56.string(),method:z56.string().nullable(),type:z56.string().nullable(),validationRecords:z56.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z56.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z56.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z56.enum(["subdomain","apex"]),RedirectConfigSchema=z56.object({type:z56.literal("apex_to_www"),linkedDomainId:z56.string()}).nullable().optional(),ProjectDomainDTOSchema=z56.object({id:z56.string(),hostname:z56.string(),status:z56.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z56.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z56.string(),scdCnameTarget:z56.string().optional(),apexTargets:z56.array(z56.string()),dnsAutoConfigured:z56.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z56.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z56.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z56.object({hostname:z56.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:z56.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z56.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z56.object({available:z56.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z56.object({success:z56.boolean(),hostname:z56.string()}))}});import{z as z57}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=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z57.object({slug:z57.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z57.object({subdomain:z57.string(),subdomainUpdatedAt:z57.coerce.date()})),SubdomainSuggestionsQuerySchema=z57.object({base:z57.string().max(100).optional(),max:z57.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z57.object({suggestions:z57.array(z57.string())}))}});import{z as z58}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=z58.object({translated:z58.number().int().nonnegative(),total:z58.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z58.object({locale:z58.string(),isDefault:z58.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z58.object({defaultLocale:z58.string(),locales:z58.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z58.object({locale:z58.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z58.object({locale:z58.string().min(1).max(40)}),ProjectLocaleMutationSchema=z58.object({locale:z58.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z58.object({locale:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z59}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=z59.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z59.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=z59.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z59.number(),credits:z59.number().optional(),billingMode:z59.enum(["fimo-credits","provider-account"]).optional(),confidence:z59.enum(["exact","estimated","metered"]),basis:z59.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z60}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=z60.object({options:z60.record(z60.string(),z60.unknown()),name:z60.string().optional(),parentId:z60.string().nullable().optional(),altText:z60.string().optional(),caption:z60.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z60.string().min(1).optional(),model:z60.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=z60.object({jobId:z60.string(),status:z60.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z60.string().nullable().optional(),credits:z60.number().optional(),costUsd:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z60.object({error:z60.string(),code:z60.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:z60.array(GenerationTaskIdSchema).optional(),availableModels:z60.array(z60.string()).optional(),issues:z60.array(z60.unknown()).optional()})}});import{z as z61}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=z61.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z61.object({name:z61.string(),key:z61.string(),description:z61.string(),type:FlagTypeSchema,required:z61.boolean(),defaultValue:z61.unknown().optional(),enumValues:z61.array(z61.string()).optional(),isArray:z61.boolean()}),AssetModelPriceSchema=z61.object({unitPrice:z61.number(),unit:z61.string(),confidence:z61.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z61.object({id:z61.string(),shortName:z61.string(),provider:z61.string(),source:z61.string(),modality:z61.enum(["image","video","audio"]),tags:z61.array(z61.string()),displayName:z61.string(),description:z61.string(),flags:z61.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z61.object({model:z61.string(),costUsd:z61.number(),credits:z61.number(),billingMode:z61.enum(["fimo-credits","provider-account"]),confidence:z61.enum(["exact","estimated","metered"]),basis:z61.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z62}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=z62.object({tourId:z62.string(),version:z62.string(),status:z62.string(),completedAt:z62.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z62.array(UserTourDTOSchema))}});import{z as z63}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=z63.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z63.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z63.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z63.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z63.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z63.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z63.enum(["user","agent","system"]),SupportReportTagSchema=z63.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z63.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z63.object({organization:z63.object({id:z63.string().trim().min(1).max(255),name:z63.string().trim().max(240).optional()}),project:z63.object({id:z63.uuid(),name:z63.string().trim().max(240).optional(),createdAt:z63.coerce.date().optional()}).optional(),environment:z63.string().trim().max(255).optional(),clientVersion:z63.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z63.string().trim().max(200).optional(),limit:z63.coerce.number().int().min(1).max(100).default(50),offset:z63.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z63.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z63.uuid().nullable().optional(),note:z63.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=z63.object({message:z63.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z63.object({kind:SupportReportLinkKindSchema,label:z63.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z63.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z63.object({kind:SupportReportActorKindSchema,id:z63.string().nullable(),name:z63.string().nullable()}),SupportReportLinkDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportLinkKindSchema,label:z63.string(),url:SupportReportHttpUrlSchema,externalId:z63.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportEventKindSchema,body:z63.string().nullable(),metadata:z63.record(z63.string(),z63.unknown()),actor:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z63.object({id:z63.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z63.array(z63.string()),source:SupportReportSourceSchema,message:z63.string(),reporter:z63.object({id:z63.string().nullable(),name:z63.string().nullable(),email:z63.string().nullable()}),organization:z63.object({id:z63.string().nullable(),name:z63.string()}),project:z63.object({id:z63.uuid().nullable(),name:z63.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z63.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z63.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z63.string().nullable(),deliveredAt:z63.coerce.date().nullable()}).nullable(),duplicateOfReportId:z63.uuid().nullable(),resolvedAt:z63.coerce.date().nullable(),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z63.string().nullable(),clientVersion:z63.string().nullable(),links:z63.array(SupportReportLinkDTOSchema),events:z63.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z63.object({reports:z63.array(SupportReportSummaryDTOSchema),total:z63.number().int().nonnegative(),statusCounts:z63.object({new:z63.number().int().nonnegative(),in_progress:z63.number().int().nonnegative(),waiting:z63.number().int().nonnegative(),resolved:z63.number().int().nonnegative(),duplicate:z63.number().int().nonnegative(),irrelevant:z63.number().int().nonnegative(),ignored:z63.number().int().nonnegative()}),limit:z63.number().int().positive(),offset:z63.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z63.object({id:z63.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z63.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z64}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=z64.iso.datetime({offset:!0}).pipe(z64.coerce.date()),OpsRecentChatInputSchema=z64.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z64.string().trim().min(1).max(255).optional(),limit:z64.coerce.number().int().min(1).max(200).default(100),cursor:z64.string().trim().min(1).max(2e3).optional(),slim:z64.boolean().default(!0),reason:z64.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=z64.object({id:z64.string(),threadId:z64.string(),providerMessageId:z64.string().nullable(),invocationId:z64.string().nullable(),env:z64.string().nullable(),role:z64.string(),parts:z64.array(z64.record(z64.string(),z64.unknown())),metadata:z64.object({status:z64.string().optional(),traceUrl:z64.string().optional(),externalFileChanges:z64.array(z64.unknown()).optional()}),stats:z64.object({toolCount:z64.number().int().nonnegative(),failedToolCount:z64.number().int().nonnegative()}),createdAt:z64.iso.datetime({offset:!0}),project:z64.object({id:z64.string(),name:z64.string(),displayName:z64.string().nullable(),organizationId:z64.string().nullable()})}),OpsRecentChatResponseSchema=z64.object({target:z64.object({backendProfile:OpsBackendProfileSchema,projectEnv:z64.string().nullable()}),window:z64.object({from:z64.iso.datetime({offset:!0}),to:z64.iso.datetime({offset:!0})}),messages:z64.object({items:z64.array(OpsRecentChatMessageSchema),nextCursor:z64.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z65}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=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z65.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z65.literal(!1),reason:z65.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z66}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z66.object({packageManager:z66.string().trim().min(1).max(200).nullable(),trackedLockfiles:z66.array(z66.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z66.string().trim().min(1)}),OpsProjectPackageManagerSchema=z66.object({target:z66.object({backendProfile:OpsBackendProfileSchema,projectId:z66.uuid(),projectEnv:z66.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z67}from"zod";function createAgentRunWebhookEventDataSchema(status){return z67.object({run:z67.object({id:z67.string(),agentName:z67.string(),trigger:z67.string(),status:z67.literal(status),startedAt:z67.string().nullable(),finishedAt:z67.string().nullable(),reason:z67.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=z67.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z67.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z67.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z67.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z67.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z67.union([z67.literal(0),z67.literal(5),z67.literal(30),z67.literal(60)]),EntryChangedWebhookEventDataSchema=z67.object({reason:WebhookEntryChangeReasonSchema,operationId:z67.string().optional(),batch:z67.object({index:z67.number().int().positive(),total:z67.number().int().positive()}).optional(),changes:z67.array(z67.object({action:WebhookEntryChangeActionSchema,contentType:z67.string(),id:z67.string(),documentId:z67.string(),locale:z67.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z67.object({form:z67.object({id:z67.string(),label:z67.string()}),submission:z67.object({id:z67.string(),data:z67.record(z67.string(),z67.unknown()),submittedAt:z67.string()})}),PublishStartedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("publishing"),startedAt:z67.string()})}),PublishSucceededWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("published"),url:z67.string(),publishedAt:z67.string(),firstPublish:z67.boolean()})}),PublishFailedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("failed"),reason:z67.string()})}),PublishUnpublishedWebhookEventDataSchema=z67.object({publication:z67.object({previousUrl:z67.string(),unpublishedAt:z67.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),classification:z67.string(),summary:z67.string(),reasons:z67.array(z67.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),resolution:z67.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z67.object({report:z67.object({weekStart:z67.string(),weekEnd:z67.string(),pageviews:z67.number(),visitors:z67.number(),previousPageviews:z67.number(),previousVisitors:z67.number()})}),MediaAssetWebhookEventDataSchema=z67.object({id:z67.string().nullable(),name:z67.string().nullable(),type:z67.string(),mimeType:z67.string().nullable(),fileSize:z67.number().nullable()}),MediaUploadedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["updated","moved","analysis"]),analysis:z67.object({category:z67.string(),status:z67.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("generated"),generation:z67.object({model:z67.string(),mode:z67.string()})}),MediaProcessingFailedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["analysis","generation"]),failure:z67.object({code:z67.string()})}),DomainCreatedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string()})}),LabelChangedWebhookEventDataSchema=z67.object({changes:z67.array(z67.object({action:z67.enum(["created","updated","deleted"]),key:z67.string(),locale:z67.string(),value:z67.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),isDefault:z67.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),previousCode:z67.string()})}),LocaleDeletedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),entriesDeleted:z67.number().int().nonnegative(),labelsDeleted:z67.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z67.object({merge:z67.object({id:z67.string(),from:EnvSchema,to:EnvSchema,applied:z67.array(z67.object({surface:SurfaceNameSchema,count:z67.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema}),version:z67.object({versionId:z67.uuid(),name:z67.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=z67.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z67.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z67.discriminatedUnion("source",[z67.object({source:z67.literal("literal"),value:z67.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z67.object({source:z67.literal("secret"),key:z67.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z67.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z67.object({name:z67.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z67.object({name:z67.string(),source:z67.enum(["literal","secret"]),secretKey:z67.string().nullable(),secretPrefix:z67.string().nullable(),configured:z67.literal(!0)}),WebhookFilterSchema=z67.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z67.string().min(1).max(255).optional(),agentName:z67.string().min(1).max(120).optional(),mediaType:z67.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z67.string().min(1).max(255).optional(),locale:z67.string().min(1).max(120).optional()}),JsonValueSchema=z67.lazy(()=>z67.union([z67.string(),z67.number(),z67.boolean(),z67.null(),z67.array(JsonValueSchema),z67.record(z67.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z67.url(),enabled:z67.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z67.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z67.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z67.url().optional(),enabled:z67.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z67.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z67.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z67.object({eventType:WebhookEventTypeSchema.optional(),data:z67.record(z67.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z67.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z67.uuid(),name:z67.string(),eventType:WebhookEventTypeSchema,enabled:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z67.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z67.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z67.coerce.date().nullable(),deliveryStats24h:z67.object({succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z67.uuid(),projectId:z67.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z67.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z67.number().int().positive(),test:z67.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z67.number().int().nonnegative(),responseStatus:z67.number().int().nullable(),lastErrorCode:z67.string().nullable(),lastErrorMessage:z67.string().nullable(),payloadAvailable:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z67.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z67.string().nullable(),qstashMessageId:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z67.object({items:z67.array(WebhookDeliveryDTOSchema),pagination:z67.object({page:z67.number().int().positive(),limit:z67.number().int().positive(),total:z67.number().int().nonnegative(),totalPages:z67.number().int().positive(),hasMore:z67.boolean()}),stats:z67.object({total:z67.number().int().nonnegative(),succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z67.object({id:z67.uuid(),deliveryId:z67.uuid(),attempt:z67.number().int().positive(),status:z67.enum(["delivering","succeeded","failed"]),responseStatus:z67.number().int().nullable(),durationMs:z67.number().int().nonnegative(),responseExcerpt:z67.string().nullable(),errorCode:z67.string().nullable(),errorMessage:z67.string().nullable(),createdAt:z67.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z67.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z67.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z68}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=z68.object({key:z68.literal("fimo-2"),enabled:z68.boolean(),dismissed:z68.boolean().default(!1),interacted:z68.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z69}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=z69.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z69.object({total:z69.number(),base:z69.number(),purchases:z69.number(),awards:z69.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z69.object({id:z69.string(),name:z69.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z69.object({type:z69.string(),brand:z69.string().nullable(),last4:z69.string().nullable(),expirationDate:z69.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z69.object({currency:z69.string(),nextPaymentAmount:z69.number().nullable(),nextPaymentAt:z69.string().nullable(),billingInterval:z69.string().nullable(),totalAmount:z69.number().nullable(),discountAmount:z69.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z69.object({id:z69.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z69.string().nullable(),currentPeriodEndsAt:z69.string().nullable(),renewsAt:z69.string().nullable(),cancelAt:z69.string().nullable(),renewAutomatically:z69.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z69.object({type:z69.enum(["low_balance","critical_balance","approaching_limit"]),message:z69.string(),estimatedPromptsRemaining:z69.number().nullable(),avgCostPerPrompt:z69.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z69.object({monthlyCredits:z69.number().nullable(),usedThisPeriod:z69.number(),remainingThisPeriod:z69.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z69.object({organizationId:z69.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z69.string().nullable(),tenureDays:z69.number().int().nonnegative(),capturedAt:z69.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z69.object({hasSubscription:z69.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z69.number().nullable(),alerts:z69.array(CreditAlertDTOSchema),portalUrl:z69.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z69.object({creditCount:z69.number().int().positive(),expiresAt:z69.string().datetime().nullable().optional(),message:z69.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("free"),amountCents:z69.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("purchase"),amountCents:z69.number().int().positive()}),CreditTopupRequestDTOSchema=z69.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z69.object({success:z69.boolean(),transactionId:z69.string().nullable(),newBalance:z69.number(),creditCount:z69.number(),type:z69.enum(["free","purchase"]),invoiceId:z69.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z70}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=z70.object({totalCredits:z70.number(),totalCostUsd:z70.number(),totalMessages:z70.number(),avgCostPerMessage:z70.number(),periodStart:z70.string().nullable(),periodEnd:z70.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z70.object({date:z70.string(),credits:z70.number(),costUsd:z70.number(),messages:z70.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z70.array(UsageByUserForProjectDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z70.object({summary:UsageSummaryDTOSchema,byProject:z70.array(UsageByProjectDTOSchema),byUser:z70.array(UsageByUserDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z71}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=z71.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z71.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z71.object({startDate:z71.string().optional(),endDate:z71.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z71.coerce.number().int().positive().default(1),limit:z71.coerce.number().int().positive().max(100).default(20),sortBy:z71.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z71.string().optional(),activeOnly:z71.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),avgCreditsPerMessage:z71.number(),periodStart:z71.string(),periodEnd:z71.string(),creditsChange:z71.number().nullable(),costChange:z71.number().nullable(),messagesChange:z71.number().nullable(),unattributedCredits:z71.number(),unattributedCostUsd:z71.number(),unattributedMessages:z71.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z71.object({organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number(),projectCount:z71.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().nullable(),userImage:z71.string().nullable(),organizationId:z71.string().nullable(),organizationName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),projectCount:z71.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z71.object({id:z71.string(),name:z71.string(),value:z71.number(),percentage:z71.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z71.object({day:z71.number(),hour:z71.number(),value:z71.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z71.object({summary:UsageOverviewSummaryDTOSchema,timeline:z71.array(UsageTimelinePointDTOSchema),topOrganizations:z71.array(OrganizationUsageRowDTOSchema),topUsers:z71.array(UserUsageRowDTOSchema),topProjects:z71.array(ProjectUsageRowDTOSchema),creditDistribution:z71.array(UsageDistributionItemDTOSchema),userDistribution:z71.array(UsageDistributionItemDTOSchema),heatmap:z71.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z71.object({page:z71.number(),limit:z71.number(),totalItems:z71.number(),totalPages:z71.number(),hasMore:z71.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z71.object({organizations:z71.array(OrganizationUsageRowDTOSchema),top:z71.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z71.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z71.object({users:z71.array(ExtendedUserUsageRowDTOSchema),top:z71.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z71.object({projects:z71.array(ExtendedProjectUsageRowDTOSchema),top:z71.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z71.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z71.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z71.object({credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),createdAt:z71.string(),memberCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z71.object({id:z71.string(),name:z71.string().nullable(),email:z71.string(),image:z71.string().nullable(),createdAt:z71.string(),organizationCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),displayName:z71.string().nullable(),createdAt:z71.string(),organizationId:z71.string(),organizationName:z71.string(),ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z72}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=z72.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z72.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z72.object({command:z72.string().min(1).max(1e4),cwd:z72.string().optional(),projectEnv:EnvSchema.optional(),env:z72.record(z72.string(),z72.string()).optional(),name:z72.string().optional(),waitForCompletion:z72.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z72.object({identifier:z72.string(),status:SandboxProcessStatusSchema,command:z72.string().optional(),startedAt:z72.string().optional(),exitCode:z72.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z72.object({processes:z72.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z72.object({processId:z72.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z72.object({success:z72.boolean(),message:z72.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z73}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_asset_reading();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_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_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_ops_project_files_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,readFile7=defaultReadFile){try{return JSON.parse(readFile7(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&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function 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:path54,message}=issue;return`${Array.isArray(path54)&&path54.length>0?`${path54.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 SandboxReadinessError,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");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path54,status,detail,code2,body){super(`API ${method} ${path54} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path54,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__name(publicationIdFromError,"publicationIdFromError");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}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(path54,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}${path54}`,{...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",path54,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path54,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}${path54}`,{...init,headers})}async rawRequest(path54,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}${path54}`,{...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"} ${path54} 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&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.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,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}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&&params.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 addProjectMcpIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations`,{method:"POST",body:JSON.stringify(input.request)})).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 connectProjectIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).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&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.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&&params.set("includeDeleted","true"),opts.includeAgentEnvs&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.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,path54,opts={}){let qs=lazyFetchQs(opts.against,{path:path54});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),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).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&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.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 getSandboxLogs(projectId,env,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,env,options={}){let params=new URLSearchParams;options.noRestart&&params.set("noRestart","true"),options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",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="",errorMessage6=null,errorCode,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
42
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{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","Pro"]),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"}});import{z as z5}from"zod";var MB,MAX_DOCUMENT_SIZE_BYTES,MAX_AUDIO_SIZE_BYTES,MAX_IMAGE_SIZE_BYTES,MAX_VIDEO_SIZE_BYTES,MAX_ARCHIVE_SIZE_BYTES,MAX_MODEL_SIZE_BYTES,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES,MODEL_MEDIA_TYPE,AttachmentModelMediaTypeSchema,MODEL_MIME_TYPES,MODEL_RENDER_VIEW_ANGLES,AttachmentModelRenderRequestSchema,AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema,AttachmentModelRenderResponseSchema,AttachmentModelRenderMeterSchema,ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";MB=1024*1024,MAX_DOCUMENT_SIZE_BYTES=5*MB,MAX_AUDIO_SIZE_BYTES=10*MB,MAX_IMAGE_SIZE_BYTES=20*MB,MAX_VIDEO_SIZE_BYTES=20*MB,MAX_ARCHIVE_SIZE_BYTES=20*MB,MAX_MODEL_SIZE_BYTES=20*MB,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES=20*MB,MODEL_MEDIA_TYPE={GLB:"model/gltf-binary",GLTF:"model/gltf+json",FBX:"model/fbx",OBJ:"model/obj",STL:"model/stl",PLY:"model/ply"},AttachmentModelMediaTypeSchema=z5.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z5.object({renderId:z5.uuid(),filename:z5.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z5.url()}),AttachmentModelRenderSuccessSchema=z5.object({status:z5.literal("succeeded"),views:z5.tuple([z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z5.url()})]),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative(),diagnostics:z5.unknown().optional()}),AttachmentModelRenderFailureSchema=z5.object({status:z5.literal("failed"),error:z5.literal("render_failed"),message:z5.string(),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative()}),AttachmentModelRenderResponseSchema=z5.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z5.object({browserElapsedMs:z5.number().nonnegative()}),ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:MAX_ARCHIVE_SIZE_BYTES},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLB,extensions:[".glb"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLTF,extensions:[".gltf"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.FBX,extensions:[".fbx"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.OBJ,extensions:[".obj"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.STL,extensions:[".stl"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.PLY,extensions:[".ply"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z6}from"zod";var AssetReadRequestSchema,AssetDerivedFileSchema,AssetReadBaseSchema,AssetReadPageSchema,AssetReadQuerySchema,AssetReadResultSchema,init_asset_reading=__esm({"../../packages/api-contracts/dist/esm/types/asset-reading.js"(){"use strict";AssetReadRequestSchema=z6.object({cursor:z6.string().optional(),query:z6.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),AssetDerivedFileSchema=z6.object({url:z6.url(),mediaType:z6.string(),filename:z6.string()}),AssetReadBaseSchema=z6.object({assetId:z6.uuid(),filename:z6.string(),mediaType:z6.string(),representation:z6.enum(["text","table","document","archive","image","transcript","video","model"]),content:z6.string(),derivedFiles:z6.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z6.literal("page"),start:z6.number().int().nonnegative(),end:z6.number().int().nonnegative(),total:z6.number().int().nonnegative(),nextCursor:z6.string().nullable(),complete:z6.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z6.literal("query"),query:z6.string(),source:z6.enum(["original-file","canonical-text","derived-files"]),truncated:z6.boolean()}),AssetReadResultSchema=z6.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z7}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=z7.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 z8}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=z8.union([z8.literal(PRODUCTION_ENVIRONMENT_KEY),z8.literal(PREVIEW_ENVIRONMENT_KEY),z8.uuid()]),CustomEnvironmentSchema=z8.object({id:z8.uuid(),projectId:z8.uuid(),name:z8.string().trim().min(1).max(64),branchPatterns:z8.array(z8.string().min(1).max(255)).min(1),description:z8.string().max(255).nullable()}),ResolvedEnvironmentSchema=z8.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});import{z as z9}from"zod";var NOTIFICATION_EVENTS,NotificationAudienceSchema,NotificationEventSchema,init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env();NOTIFICATION_EVENTS={created:"notifications/created",stateChanged:"notifications/state-changed",unreadChanged:"notifications/unread-changed"},NotificationAudienceSchema=z9.object({projectId:z9.uuid(),userId:z9.string().min(1)}),NotificationEventSchema=z9.discriminatedUnion("type",[z9.object({type:z9.literal(NOTIFICATION_EVENTS.created),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.stateChanged),payload:NotificationAudienceSchema.extend({notificationId:z9.uuid()})}),z9.object({type:z9.literal(NOTIFICATION_EVENTS.unreadChanged),payload:NotificationAudienceSchema})])}});import{z as z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";function 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,path54){let conditionPath=[...path54,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,path54)=>{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,path54));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path54,fieldName,variant.uid]);else walk(field.schema.fields,[...path54,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path54,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path54,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=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),group:z11.union([z11.string().min(1),z11.array(z11.string().min(1)).min(1)]).optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type==="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=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_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_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_agent_provider_errors_read","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_billing_legacy_premium_enroll","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","env","project","day"]),OpsAgentHealthInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),env:z13.string().trim().min(1).max(64).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),reason:z13.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsBillingCacheInvalidateInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z13.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z13.object({path:OpsProjectFilePathSchema,content:z13.string().max(256*1024),overwrite:z13.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z13.string().trim().length(64),consentReference:z13.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z13.intersection(OpsProjectOperationPlanInputSchema,z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z13.object({planHash:z13.string().trim().length(64),reason:z13.string().trim().min(1).max(1e3),consentReference:z13.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z14}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z14.object({kind:z14.literal("say"),label:z14.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z14.string().min(1).max(240).optional(),message:z14.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z14.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z14.discriminatedUnion("command",[z14.object({kind:z14.literal("app"),command:z14.literal("publish")}).strict(),z14.object({kind:z14.literal("app"),command:z14.literal("connect"),integrationKey:z14.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z14.object({fallback:z14.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z14.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z14.literal("choices"),text:z14.string().max(500).optional(),actions:z14.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z14.discriminatedUnion("kind",[z14.object({kind:z14.literal("entry"),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("asset"),assetId:z14.string().min(1).max(120)}),z14.object({kind:z14.literal("url"),url:z14.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z14.literal("table"),columns:z14.array(z14.object({label:z14.string().min(1).max(24)})).min(2).max(4),rows:z14.array(z14.object({cells:z14.array(z14.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:z14.literal("cards"),layout:z14.enum(["rail","stack"]).optional(),items:z14.array(z14.object({title:z14.string().min(1).max(60),subtitle:z14.string().min(1).max(120).optional(),imageUrl:z14.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z14.literal("entry"),label:z14.string().min(1).max(80),collection:z14.string().min(1).max(80),entryId:z14.string().min(1).max(120),path:z14.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z14.literal("assets"),items:z14.array(z14.object({url:z14.url({protocol:/^https$/}).max(2e3),alt:z14.string().min(1).max(120),label:z14.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z14.literal("callout"),title:z14.string().min(1).max(80),text:z14.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z14.literal("stat"),items:z14.array(z14.object({label:z14.string().min(1).max(24),value:z14.string().min(1).max(16),delta:z14.string().min(1).max(12).optional(),tone:z14.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z14.literal("chart"),unit:z14.string().min(1).max(12).optional(),points:z14.array(z14.object({label:z14.string().min(1).max(12),value:z14.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z14.literal("text"),placeholder:z14.string().min(1).max(120).optional(),multiline:z14.boolean().optional()}).strict(),ChatFormStepIdSchema=z14.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z14.object({id:ChatFormStepIdSchema,token:z14.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z14.string().trim().min(1).max(60),reason:z14.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z14.literal("capabilities"),items:z14.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z14.object({id:ChatFormStepIdSchema.optional(),question:z14.string().min(1).max(500),header:z14.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z14.boolean(),recommended:z14.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."}),step.body.type==="capabilities"&&!step.multiSelect&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}),FormBlockSchema=BlockBaseSchema.extend({type:z14.literal("form"),steps:z14.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z14.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z14.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z14.object({stepId:ChatFormStepIdSchema.optional(),header:z14.string().min(1).max(25),question:z14.string().min(1).max(500),answer:z14.string().min(1),selectedLabels:z14.array(z14.string().min(1).max(120)).max(8),freeText:z14.string(),skipped:z14.boolean()}),ChatFormAnswerMetadataSchema=z14.object({toolCallId:z14.string().max(255).optional(),shortTitle:z14.string().max(80).optional(),questions:z14.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z14.object({version:z14.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z14.string().min(1).max(255)})}});import{z as z15}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z15.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z15.object({dev:z15.string().trim().min(1).optional(),build:z15.string().trim().min(1).optional(),install:z15.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z15.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z15.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z15.object({type:z15.enum(["header","cookie","query","host"]),key:z15.string().min(1).optional(),value:z15.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z15.array(FimoHostingConditionSchema).min(1).optional(),missing:z15.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z15.object({source:z15.string().min(1),destination:z15.string().min(1),permanent:z15.boolean().optional(),statusCode:z15.union([z15.literal(301),z15.literal(302),z15.literal(307),z15.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z15.object({source:z15.string().min(1),headers:z15.array(z15.object({key:z15.string().min(1),value:z15.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z15.object({rewrites:z15.array(FimoHostingRewriteSchema).optional(),redirects:z15.array(FimoHostingRedirectSchema).optional(),headers:z15.array(FimoHostingHeaderSchema).optional(),cleanUrls:z15.boolean().optional(),trailingSlash:z15.boolean().optional()}).strict(),FimoAppConfigSchema=z15.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(path54){return[...path54.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path54){return pageRouteParamNames(path54).filter(param=>!LOCALE_PARAM_NAME.test(param))}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});import{z as z16}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,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_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=z16.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z16.string(),displayName:z16.string().nullable(),subdomain:z16.string().nullable().optional(),subdomainUpdatedAt:z16.date().nullable().optional(),organizationId:z16.string().nullable(),createdBy:z16.string().nullable(),previewEnabled:z16.boolean().default(!0),enabledChatModels:z16.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z16.string(),thumbnailUrl:z16.string().nullable(),publishedThumbnailUrl:z16.string().nullable(),category:z16.string().nullable(),appUrl:z16.string().nullable(),lastPublishedAt:z16.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z16.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z16.object({id:z16.uuid(),name:z16.string(),displayName:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),category:z16.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z16.object({id:z16.string(),name:z16.string(),avatar:z16.string().nullable(),color:z16.object({bg:z16.string(),text:z16.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z16.object({path:z16.string(),content:z16.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z16.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z16.object({id:z16.string(),messageId:z16.string(),versionId:z16.string().nullable(),role:ProjectChatMessageRole,parts:z16.array(z16.any()),createdAt:z16.coerce.date()}),MessageUserMetadataSchema=z16.object({id:z16.string(),name:z16.string().nullable().optional(),image:z16.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z16.number(),metadata:z16.object({user:MessageUserMetadataSchema,changeManifest:z16.array(z16.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z16.object({versionId:z16.uuid(),commitHash:z16.string(),name:z16.string(),description:z16.string().nullable(),kind:z16.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z16.object({versionCount:z16.number().int().nonnegative(),snapshotBytes:z16.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z16.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z16.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z16.object({content:z16.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z16.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z16.object({success:z16.boolean(),message:z16.string().optional(),warning:z16.string().optional(),durationMs:z16.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z16.object({isPublished:z16.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z16.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z16.object({label:z16.string().trim().min(1).max(120).optional(),notes:z16.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z16.object({success:z16.boolean(),message:z16.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z16.boolean(),publicationId:z16.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z17}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=z17.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z17.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z17.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,parentEnv:EnvSchema.nullable(),createdBy:z17.string().nullable(),deletedAt:z17.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z17.object({id:z17.union([z17.literal(PREVIEW_ENVIRONMENT_KEY),z17.uuid()]),name:z17.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z17.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z17.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z17.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z17.object({surface:z17.enum(["code","schemas","content","translations","assets","forms"]),status:z17.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z17.number().int().nonnegative(),conflictCount:z17.number().int().nonnegative()}),EnvDiffResultSchema=z17.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z17.coerce.date(),surfaces:z17.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z18}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=z18.object({projectId:z18.uuid(),name:z18.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z18.literal("production"),sourceBranch:EnvSchema,isPublished:z18.boolean(),url:z18.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z18.literal(PREVIEW_ENVIRONMENT_KEY),kind:z18.literal("preview"),matchedBranchCount:z18.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z18.literal("custom"),matchedBranchCount:z18.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z18.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z18.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z18.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z18.object({deletedId:z18.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z19}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=z19.object({kind:z19.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z19.object({kind:z19.enum(["variable","secret"]),value:z19.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z19.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z19.object({kind:z19.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),key:z19.string(),kind:z19.literal("secret"),exposure:z19.literal("private"),environment:EnvironmentKeySchema,maskedValue:z19.string().optional(),createdAt:z19.date().transform(value=>value.toISOString()),updatedAt:z19.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z19.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z20}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=z20.object({success:z20.literal(!0),downloadUrl:z20.string(),expiresAt:z20.string(),fileSize:z20.number(),duration:z20.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z20.object({success:z20.literal(!0),projectId:z20.string(),projectName:z20.string(),displayName:z20.string(),projectUrl:z20.string(),duration:z20.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z20.object({contentTypes:z20.number(),entries:z20.number(),assets:z20.number(),translations:z20.number(),forms:z20.number(),codeFiles:z20.number(),assetFiles:z20.number()}),ImportPreviewSurfaceDTOSchema=z20.object({name:z20.string(),included:z20.boolean(),count:z20.number().optional(),note:z20.string().optional()}),ImportPreviewDTOSchema=z20.object({projectName:z20.string(),displayName:z20.string().nullable(),category:z20.string().nullable(),exportedAt:z20.string(),version:z20.string(),envScope:z20.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z20.array(ImportPreviewSurfaceDTOSchema),fileSize:z20.number(),fileName:z20.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z20.object({success:z20.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z21}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=z21.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z21.object({type:z21.literal("manual")}),ScheduleTriggerSchema=z21.object({type:z21.literal("schedule"),cron:z21.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:z21.string().optional()}),WebhookTriggerSchema=z21.object({type:z21.literal("webhook"),path:z21.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z21.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z22}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=z22.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z22.object({token:z22.string().min(1),risk:CapabilityRiskTierSchema,description:z22.string()}),AgentSubAgentSummarySchema=z22.object({name:z22.string().min(1),grant:z22.enum(["inherit","explicit"]),effectiveCaps:z22.array(z22.string().min(1))}),AgentInstallSummaryDTOSchema=z22.object({agentName:z22.string().min(1),env:z22.string().min(1),declaredCapabilities:z22.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z22.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z22.array(CapabilitySummaryEntrySchema),criticalCapabilities:z22.array(CapabilitySummaryEntrySchema),subAgents:z22.array(AgentSubAgentSummarySchema),declaresDelegate:z22.boolean(),cycle:z22.array(z22.string()).nullable(),missingSubAgents:z22.array(z22.string()),warnings:z22.array(z22.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z23}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=z23.object({kind:TriggerKindSchema,summary:z23.string()}),AgentListItemTriggerStateSchema=z23.object({triggerIndex:z23.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z23.boolean(),wired:z23.boolean(),syncError:z23.string().nullable()}),AgentListItemDTOSchema=z23.object({name:z23.string().min(1),description:z23.string().nullable(),goalFirstLine:z23.string().nullable(),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),triggers:z23.array(AgentListItemTriggerSchema),triggerStates:z23.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z23.array(AgentListItemDTOSchema))}});import{z as z24}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=z24.object({args:z24.unknown().optional(),requestId:z24.string().min(1).max(128).optional()}),DispatchSkippedSchema=z24.object({skipped:z24.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z24.object({sessionId:z24.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z24.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z25}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=z25.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z25.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z25.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z25.object({verb:SurfaceDeltaVerbSchema,key:z25.string(),detail:z25.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z25.record(z25.string(),z25.unknown()).optional()}),PerSurfaceDeltaSchema=z25.object({surface:SurfaceNameSchema,status:z25.enum(["ok","timed_out","failed","unchanged"]),durationMs:z25.number().int().nonnegative().optional(),changedCount:z25.number().int().nonnegative(),conflictCount:z25.number().int().nonnegative(),items:z25.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z25.boolean().optional(),error:z25.string().optional()}),CrossSurfaceFindingSchema=z25.object({id:z25.string(),kind:z25.string(),description:z25.string(),severity:z25.enum(["warning","error"]),source:z25.object({surface:SurfaceNameSchema,key:z25.string()}),target:z25.object({surface:SurfaceNameSchema,key:z25.string()}),actions:z25.array(z25.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z25.object({env:EnvSchema,vs:EnvSchema,syncState:z25.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),agents:z25.array(z25.object({id:z25.string(),name:z25.string(),status:z25.enum(["active","paused","failed"]),lastRunAt:z25.coerce.date().nullable()})).optional(),crossSurface:z25.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z25.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z25.coerce.date(),surfaces:z25.array(PerSurfaceDeltaSchema),crossSurface:z25.array(CrossSurfaceFindingSchema).optional(),fingerprint:z25.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z25.object({path:z25.string(),state:z25.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z25.string(),additions:z25.number().int().nonnegative(),deletions:z25.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z25.object({oid:z25.string().optional(),content:z25.string().optional(),truncated:z25.boolean(),binary:z25.boolean()}),CodeConflictDetailSchema=z25.object({path:z25.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z25.string(),targetTipSha:z25.string(),mergeBaseSha:z25.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z25.object({id:z25.string(),slug:z25.string(),contentType:z25.string(),data:z25.record(z25.string(),z25.unknown()),updatedAt:z25.coerce.date()}),ContentRowDiffSchema=z25.object({collection:z25.string(),rowId:z25.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z25.object({name:z25.string(),label:z25.string(),isSingleton:z25.boolean(),fields:z25.record(z25.string(),z25.unknown())}),SchemaTypeDiffSchema=z25.object({typeName:z25.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z25.object({id:z25.string(),name:z25.string(),type:z25.enum(["file","folder"]),mimeType:z25.string().nullable(),storageKey:z25.string().nullable(),url:z25.string().nullable(),fileSize:z25.number().nullable(),width:z25.number().nullable(),height:z25.number().nullable(),altText:z25.string().nullable(),caption:z25.string().nullable(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),AssetDiffSchema=z25.object({assetId:z25.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z25.object({locale:z25.string(),key:z25.string(),parent:z25.string().nullable(),child:z25.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z25.object({formName:z25.string(),label:z25.string().nullable(),schemaFingerprint:z25.string(),fields:z25.record(z25.string(),z25.unknown()),settings:z25.record(z25.string(),z25.unknown()).optional()}),FormSchemaDiffSchema=z25.object({formName:z25.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=z25.enum(CONFLICT_KINDS),ConflictSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),kind:ConflictKindSchema.optional(),description:z25.string(),parentValue:z25.unknown().optional(),childValue:z25.unknown().optional(),conflictingFields:z25.array(z25.string()).optional(),code:z25.object({path:z25.string(),unresolvable:z25.boolean().optional(),reason:z25.string().optional()}).optional()}),FieldPickSchema=z25.object({field:z25.string(),choice:z25.enum(["parent","child","pick","ai-pick"]),pickedValue:z25.unknown().optional(),aiSessionId:z25.string().optional()}),ConflictResolutionSchema=z25.object({surface:SurfaceNameSchema,key:z25.string(),choice:z25.enum(["parent","child","pick"]),pickedValue:z25.unknown().optional(),fieldPicks:z25.array(FieldPickSchema).optional()}),MergeResultSchema=z25.object({ok:z25.boolean(),mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z25.array(z25.object({surface:SurfaceNameSchema,count:z25.number().int().nonnegative()})),conflicts:z25.array(ConflictSchema).optional(),summary:z25.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z25.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z25.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z25.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z25.boolean().optional()}),ResolvedStrategySchema=z25.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z25.boolean()}),MergeRequestSchema=z25.object({from:EnvSchema,allowDirectMerge:z25.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z25.object({mergeId:z25.string().uuid(),streamUrl:z25.string(),strategy:ResolvedStrategySchema,acceptedAt:z25.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z25.object({mergeId:z25.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z25.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z25.array(ConflictSchema),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedBy:z25.string().nullable(),lastEditedAt:z25.coerce.date().nullable(),initiator:z25.object({userId:z25.string().nullable(),role:z25.string().nullable(),agentName:z25.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z25.object({resolutions:z25.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z25.object({mergeId:z25.string().uuid(),draftResolutions:z25.array(ConflictResolutionSchema),lastEditedAt:z25.coerce.date(),lastEditedBy:z25.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z25.object({mergeId:z25.string().uuid(),resolutions:z25.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z25.object({mergeId:z25.string().uuid()}),PublishReleaseRequestSchema=z25.object({version:z25.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z25.string().max(2e4).optional()}),PublishReleaseResultSchema=z25.object({releaseTag:z25.string(),sha:z25.string(),publishedAt:z25.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z26}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=z26.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z26.object({cpuMs:z26.number().nonnegative().default(0),netBytes:z26.number().nonnegative().default(0),walltimeMs:z26.number().nonnegative().default(0),llmTokensIn:z26.number().nonnegative().optional(),llmTokensOut:z26.number().nonnegative().optional(),stepCount:z26.number().int().nonnegative().optional(),toolCallCounts:z26.record(z26.string().min(1).max(120),z26.number().int().nonnegative()).optional(),toolCallOutcomes:z26.array(z26.object({toolName:z26.string().min(1).max(120),success:z26.boolean(),code:z26.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z26.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z26.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z26.object({capturedAt:z26.coerce.date(),fingerprint:z26.string().min(1).max(256),counts:z26.object({code:z26.number().int().nonnegative(),content:z26.number().int().nonnegative(),schemas:z26.number().int().nonnegative(),labels:z26.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z26.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z26.object({diff:DiffReportSchema,code:z26.array(CodeFileDiffSchema.extend({raw:z26.string().max(24576)})).max(200),schemas:z26.array(SchemaTypeDiffSchema).max(200),content:z26.array(z26.object({key:z26.string().min(1).max(512),collection:z26.string().min(1).max(256),slug:z26.string().max(512).optional(),verb:z26.enum(["added","modified","deleted"]),fields:z26.array(z26.object({name:z26.string().min(1).max(256),before:z26.unknown().optional(),after:z26.unknown().optional()})).max(20)})).max(200),labels:z26.array(z26.object({key:z26.string().min(1).max(512),locale:z26.string().min(1).max(64).optional(),before:z26.unknown().nullable(),after:z26.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),env:EnvSchema,agentName:z26.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z26.unknown().optional(),capabilities:z26.array(z26.string()).optional(),dataSources:z26.array(z26.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z26.string().nullable(),startedAt:z26.coerce.date().nullable(),finishedAt:z26.coerce.date().nullable(),cancelledAt:z26.coerce.date().nullable(),costUsd:z26.number().nonnegative(),costCeilingUsd:z26.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z26.boolean(),lastCheckpointId:z26.uuid().nullable(),branchEnvId:z26.uuid().nullable(),parentSessionId:z26.uuid().nullable(),terminalReason:z26.string().nullable(),errorMessage:z26.string().nullable(),report:z26.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z26.object({id:z26.uuid(),sessionId:z26.uuid(),checkpointIdx:z26.number().int().nonnegative(),payloadRef:z26.string(),payloadSizeBytes:z26.number().int().nonnegative(),checksum:z26.string().length(64),createdAt:z26.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z26.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z26.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z26.object({session:AgentSessionDTOSchema,checkpoints:z26.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z26.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","agent_runtime_allowance_exhausted"]),CancelSessionRequestSchema=z26.object({reason:z26.string().min(1).max(120).optional()})}});import{z as z27}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=z27.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z27.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z27.object({id:z27.uuid(),envId:z27.uuid(),sessionId:z27.uuid().nullable(),skillName:z27.string().min(1),classification:AgentBranchClassificationSchema,rationale:z27.string().nullable(),summary:z27.string().nullable(),surfaceDeltas:z27.record(z27.string(),z27.unknown()),createdAt:z27.coerce.date(),decidedAt:z27.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z27.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z27.object({path:z27.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z27.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z27.object({code:z27.literal("merge_conflict"),message:z27.string(),conflicts:z27.record(z27.string(),z27.number().int().nonnegative())})}});import{z as z28}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z28.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z28.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z28.object({description:z28.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z28.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z28.object({id:z28.uuid(),projectId:z28.uuid(),threadId:z28.uuid(),invocationId:z28.uuid(),agentKey:z28.string().min(1).max(120),anchorEnv:z28.string().min(1).max(64),retainedEnv:z28.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z28.string().min(1).nullable(),continuationInvocationId:z28.uuid().nullable(),askedAt:z28.coerce.date(),expiresAt:z28.coerce.date(),closedAt:z28.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z28.object({questionId:z28.uuid(),invocationId:z28.uuid(),askedAt:z28.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z28.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z28.object({question:AgentQuestionSchema,continuationInvocationId:z28.uuid(),deduped:z28.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z29}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,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z29.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z29.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z29.enum(["secret_text"]),IntegrationCredentialUsageSchema=z29.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z29.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z29.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z29.object({mode:IntegrationAuthModeSchema,label:z29.string().min(1),description:z29.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z29.object({id:z29.string().min(1),label:z29.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z29.boolean()}),IntegrationToolDefinitionDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),description:z29.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z29.object({title:z29.string().min(1),description:z29.string().min(1),command:z29.string().min(1).optional()}),IntegrationInfoDTOSchema=z29.object({key:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),type:z29.enum(["native","mcp"]).optional(),url:z29.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z29.array(IntegrationAuthModeDTOSchema),credentials:z29.array(IntegrationCredentialDefinitionDTOSchema),tools:z29.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z29.enum(["available","unavailable"]).optional(),recipes:z29.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),name:z29.string().min(1),summary:z29.string().min(1),installed:z29.boolean(),enabled:z29.boolean(),setupState:z29.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z29.string().nullable(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),connectionStatus:z29.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),installedAt:z29.coerce.date().nullable(),updatedAt:z29.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),enabled:z29.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z29.string(),connectionId:z29.uuid().nullable().optional(),connectionAlias:z29.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z29.array(z29.string()),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z29.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z29.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z29.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z29.object({value:z29.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z29.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z29.object({id:z29.uuid(),organizationId:z29.string().min(1),integrationKey:z29.string().min(1),alias:z29.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z29.string().min(1),externalAccountName:z29.string().nullable(),externalBotUserId:z29.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z29.array(z29.string()),connectedAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z29.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z29.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z29.record(McpHeaderNameSchema,z29.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z29.object({alias:z29.string().min(1).max(120).optional(),token:z29.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z29.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z29.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),alias:z29.string().min(1).max(120),token:z29.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z29.boolean().optional()}),z29.object({mode:z29.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z29.boolean().optional()})]).superRefine((value,ctx)=>{value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z29.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z29.union([z29.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z29.object({type:z29.literal("mcp"),name:z29.string().trim().min(1).max(120),url:z29.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z29.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z29.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z29.object({integrationKey:z29.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z29.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z29.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z29.literal("oauth"),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()})]),ReusableMcpServerAuthKindSchema=z29.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z29.object({id:z29.uuid(),name:z29.string().min(1),host:z29.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z29.string().min(1),availability:z29.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z29.object({query:z29.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z29.object({serverId:z29.uuid()}),StartProjectIntegrationConnectResponseSchema=z29.object({integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z29.discriminatedUnion("mode",[z29.object({mode:z29.literal("personal"),integrationKey:z29.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z29.object({mode:z29.literal("oauth"),integrationKey:z29.string().min(1),connectUrl:z29.string().url(),expiresAt:z29.coerce.date()})]),BindProjectChannelRequestSchema=z29.object({ref:z29.string().min(1),connectionAlias:z29.string().min(1).optional(),agentName:z29.string().min(1).max(160).nullable().optional(),force:z29.boolean().optional()}),ListProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1)}),SearchProjectChannelsQuerySchema=z29.object({integrationKey:z29.string().min(1),connectionAlias:z29.string().min(1),query:z29.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),integrationKey:z29.string().min(1),connectionId:z29.uuid(),externalWorkspaceId:z29.string().min(1),externalChannelId:z29.string().min(1),externalChannelName:z29.string().nullable(),agentName:z29.string().nullable(),enabled:z29.boolean(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z29.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z29.object({id:z29.string().min(1),name:z29.string().min(1),visibility:z29.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z29.string().min(1).nullable(),canMove:z29.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z29.object({markdown:z29.boolean().optional(),summary:z29.boolean().optional(),links:z29.boolean().optional(),branding:z29.boolean().optional(),images:z29.boolean().optional(),html:z29.union([z29.literal("cleaned"),z29.literal("raw"),z29.boolean()]).optional(),json:z29.union([z29.boolean(),z29.object({prompt:z29.string().min(1).max(1e4),schema:z29.record(z29.string(),z29.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z29.object({url:z29.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z29.object({query:z29.string().min(1),maxResults:z29.number().int().positive().max(20).optional(),sources:z29.array(z29.enum(["web","news","images"])).min(1).max(3).optional(),categories:z29.array(z29.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z29.enum(["hour","day","week","month","year"]).optional(),location:z29.string().min(1).max(160).optional(),country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(100).optional(),types:z29.array(z29.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),sources:z29.array(z29.string().min(1).max(512)).min(1).max(20).optional(),passages:z29.number().int().min(1).max(5).optional(),skills:z29.literal("only").optional(),language:z29.string().min(1).optional(),topic:z29.string().min(1).optional(),license:z29.string().min(1).optional(),minStars:z29.number().int().min(0).optional(),maxStars:z29.number().int().min(0).optional(),archived:z29.boolean().optional(),fork:z29.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z29.object({query:z29.string().min(1).max(500),maxResults:z29.number().int().min(1).max(500).optional(),authors:z29.array(z29.string().min(1)).min(1).optional(),categories:z29.array(z29.string().min(1)).min(1).optional(),from:z29.iso.date().optional(),to:z29.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),query:z29.string().min(1).max(500).optional(),maxPassages:z29.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z29.object({paperId:z29.string().min(1).max(512),intent:z29.string().min(1).max(500),mode:z29.enum(["similar","citers","references"]).optional(),maxResults:z29.number().int().min(1).max(500).optional(),rerank:z29.boolean().optional(),anchors:z29.array(z29.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z29.object({url:z29.string().url(),search:z29.string().min(1).optional(),limit:z29.number().int().positive().max(200).optional(),includeSubdomains:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z29.object({url:z29.string().url(),limit:z29.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z29.object({text:z29.string().min(1).max(200).optional(),cron:z29.string().min(1).max(120).optional(),timezone:z29.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z29.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z29.boolean().optional(),timeoutMs:z29.number().int().positive().max(12e4).optional(),waitForMs:z29.number().int().min(0).max(3e4).optional(),maxAgeMs:z29.number().int().min(0).optional(),minAgeMs:z29.number().int().min(0).optional(),storeInCache:z29.boolean().optional(),proxy:z29.enum(["basic","enhanced","auto"]).optional(),mobile:z29.boolean().optional(),location:z29.object({country:z29.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z29.array(z29.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z29.union([z29.object({type:z29.enum(["scrape","crawl"]).default("scrape"),urls:z29.array(z29.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z29.object({type:z29.literal("search"),queries:z29.array(z29.string().min(1).max(256)).min(1).max(12),searchWindow:z29.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z29.number().int().min(1).max(50).optional(),includeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z29.array(z29.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z29.object({name:z29.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),notification:z29.object({email:z29.object({enabled:z29.boolean().default(!0),recipients:z29.array(z29.string().email()).min(1).max(20),includeDiffs:z29.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z29.object({monitorId:z29.string().uuid(),name:z29.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z29.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z29.string().min(1).max(2e3).optional(),judgeEnabled:z29.boolean().optional(),retentionDays:z29.number().int().min(1).max(365).optional(),status:z29.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z29.object({monitorId:z29.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z29.string().uuid()}),RunProjectIntegrationToolRequestSchema=z29.object({tool:z29.string().min(1),input:z29.record(z29.string(),z29.unknown()),connectionAlias:z29.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z29.object({provider:z29.string().min(1),providerCredits:z29.number().nonnegative().optional(),providerCostUsd:z29.number().nonnegative().optional(),requests:z29.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z29.object({credits:z29.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),json:z29.unknown().optional(),branding:z29.record(z29.string(),z29.unknown()).optional(),warning:z29.string().optional()}),FirecrawlSearchToolOutputSchema=z29.object({query:z29.string(),provider:z29.literal("firecrawl"),warning:z29.string().optional(),results:z29.array(z29.object({title:z29.string(),url:z29.string(),snippet:z29.string().optional(),content:z29.string().optional(),score:z29.number().optional(),publishedAt:z29.string().optional()}))}),FirecrawlResearchPaperSchema=z29.object({paperId:z29.string(),primaryId:z29.string().optional(),ids:z29.record(z29.string(),z29.array(z29.string())).optional(),title:z29.string().optional(),abstract:z29.string().optional(),score:z29.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z29.object({text:z29.string(),score:z29.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(z29.object({id:z29.string(),type:z29.string().min(1).optional(),url:z29.string(),title:z29.string().optional(),passages:z29.array(z29.object({text:z29.string()}).passthrough())}).passthrough()),coverage:z29.record(z29.string(),z29.string()).optional(),reranked:z29.boolean().optional(),repos:z29.array(z29.record(z29.string(),z29.unknown())).optional(),sources:z29.array(z29.record(z29.string(),z29.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),paper:z29.record(z29.string(),z29.unknown()),paperId:z29.string().optional(),query:z29.string().optional(),passages:z29.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),results:z29.array(FirecrawlResearchPaperSchema),poolSize:z29.number().int().nonnegative(),truncated:z29.boolean(),note:z29.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),count:z29.number(),links:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),description:z29.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z29.object({url:z29.string(),provider:z29.literal("firecrawl"),total:z29.number(),pages:z29.array(z29.object({url:z29.string(),title:z29.string().optional(),statusCode:z29.number().optional(),markdown:z29.string().optional(),summary:z29.string().optional(),links:z29.array(z29.string()).optional(),images:z29.array(z29.string()).optional(),html:z29.string().optional(),warning:z29.string().optional()})),warning:z29.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z29.object({cron:z29.string().optional(),text:z29.string().optional(),timezone:z29.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z29.object({id:z29.string().optional(),type:z29.enum(["scrape","crawl","search"]).optional(),urls:z29.array(z29.string()).optional(),queries:z29.array(z29.string()).optional(),searchWindow:z29.string().optional(),maxResults:z29.number().optional(),includeDomains:z29.array(z29.string()).optional(),excludeDomains:z29.array(z29.string()).optional(),scrapeOptions:z29.record(z29.string(),z29.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z29.object({id:z29.string(),name:z29.string(),status:z29.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z29.string().nullable().optional(),lastRunAt:z29.string().nullable().optional(),currentCheckId:z29.string().nullable().optional(),targets:z29.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z29.string().nullable().optional(),judgeEnabled:z29.boolean().optional(),estimatedCreditsPerMonth:z29.number().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z29.object({id:z29.string(),monitorId:z29.string(),scheduledFor:z29.string().nullable().optional(),startedAt:z29.string().nullable().optional(),finishedAt:z29.string().nullable().optional(),estimatedCredits:z29.number().optional(),reservedCredits:z29.number().optional(),actualCredits:z29.number().optional(),billingStatus:z29.string().nullable().optional(),summary:z29.object({totalPages:z29.number().optional(),same:z29.number().optional(),changed:z29.number().optional(),new:z29.number().optional(),removed:z29.number().optional(),error:z29.number().optional()}).passthrough().optional(),error:z29.string().nullable().optional(),createdAt:z29.string().optional(),updatedAt:z29.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitors:z29.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),deleted:z29.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),checks:z29.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z29.object({provider:z29.literal("firecrawl"),monitorId:z29.string(),check:FirecrawlMonitorCheckOutputSchema,next:z29.string().optional()}),FirecrawlToolKeySchema=z29.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z29.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z29.object({projectId:z29.uuid(),integrationKey:z29.string().min(1),tool:z29.string().min(1),connectionAlias:z29.string().min(1).nullable().optional(),output:z29.record(z29.string(),z29.unknown()),executedAt:z29.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z29.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z29.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z29.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z29.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z29.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z29.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z29.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z29.array(ProjectChannelCandidateDTOSchema))}});import{z as z30}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=z30.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z30.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z30.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z30.object({userId:z30.string().min(1),name:z30.string(),email:z30.string().min(1),subscribed:z30.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z30.object({maxSubscribers:z30.number().int().positive(),subscriberCount:z30.number().int().nonnegative(),effectiveRecipientCount:z30.number().int().nonnegative(),currentUserSubscribed:z30.boolean(),candidates:z30.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z30.object({userIds:z30.array(z30.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z30.object({topic:UserManagedNotificationTopicSchema,enabled:z30.boolean(),source:z30.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z30.object({topics:z30.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z30.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z30.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z30.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z30.string().nullable(),maskedEmail:z30.string().min(1),applied:z30.boolean(),expiresAt:z30.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z30.object({scheduleId:z30.string().min(1),scheduleName:z30.string(),projectId:z30.string().min(1),projectName:z30.string(),env:z30.string().min(1)}),FollowedSchedulesSchema=z30.object({schedules:z30.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z31}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=z31.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=z31.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z31.uuid(),env:z31.string().min(1),name:z31.string().min(1),cron:z31.string().min(1),command:z31.string().min(1),secretKeys:z31.array(z31.string().min(1)),enabled:z31.boolean(),lastRunAt:z31.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z31.string().nullable(),overPolicyReasons:z31.array(z31.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120),cron:z31.string().min(1).max(120),command:z31.string().min(1).max(500),secretKeys:z31.array(ProjectSecretKeySchema).default([]),enabled:z31.boolean().optional()}),UpdateProjectScheduleRequestSchema=z31.object({name:z31.string().min(1).max(120).optional(),cron:z31.string().min(1).max(120).optional(),command:z31.string().min(1).max(500).optional(),secretKeys:z31.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z31.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z31.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z31.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z31.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z31.object({maxRuns:z31.number().int().positive(),retentionDays:z31.number().int().positive().nullable(),outputRetentionDays:z31.number().int().positive(),maxOutputBytes:z31.number().int().positive()}),SchedulePolicyStateSchema=z31.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z31.object({code:z31.enum(["Free","Premium","Pro"]),source:z31.enum(["cached_subscription","free_fallback"]),activeSchedules:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),concurrency:z31.object({used:z31.number().int().nonnegative(),limit:z31.number().int().positive()}),compute:z31.object({settledMs:z31.number().int().nonnegative(),reservedMs:z31.number().int().nonnegative(),includedMs:z31.number().int().positive(),remainingMs:z31.number().int().nonnegative(),resetsAt:z31.coerce.date()}),upgrade:z31.object({code:z31.literal("Pro"),activeSchedulesLimit:z31.number().int().positive(),minCadenceMinutes:z31.number().int().positive(),maxRunMs:z31.number().int().positive(),maxConcurrentRuns:z31.number().int().positive(),computeIncludedMs:z31.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z31.array(z31.string())}),ProjectScheduleUsageSchema=z31.object({runCount:z31.number().int().nonnegative(),runsWithOutput:z31.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z31.object({id:z31.uuid(),scheduleId:z31.uuid(),projectId:z31.uuid(),env:z31.string().min(1),scheduleName:z31.string().min(1),command:z31.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z31.object({id:z31.string().min(1),name:z31.string().min(1)}).nullable(),queuedAt:z31.coerce.date(),startedAt:z31.coerce.date().nullable(),finishedAt:z31.coerce.date().nullable(),exitCode:z31.number().int().nullable(),errorCode:z31.string().nullable(),error:z31.string().nullable(),outputBytes:z31.number().int().nonnegative(),outputTruncated:z31.boolean(),outputExpiresAt:z31.coerce.date().nullable(),metadataExpiresAt:z31.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z31.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z31.coerce.date().nullable(),items:z31.array(z31.object({key:z31.string().min(1),updatedAt:z31.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z31.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z31.object({trigger:z31.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z31.object({limit:z31.coerce.number().int().min(1).max(100).default(25),cursor:z31.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z31.object({items:z31.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z31.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z31.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z31.object({items:z31.array(ProjectScheduleRunDTOSchema),nextCursor:z31.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z32}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationRecipientStateSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,WorkNotificationPreferencesSchema,WorkNotificationPreferencesResponseSchema,NotificationSubjectSchema,NotificationViewSchema,NotificationViewResponseSchema,NotificationListSchema,NotificationListResponseSchema,ListNotificationsQuerySchema,NotificationStateSchema,NotificationStateResponseSchema,UpdateNotificationStateRequestSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z32.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z32.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z32.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("user"),userId:z32.string().min(1)}).strict(),z32.object({kind:z32.literal("agent"),agentKey:z32.string().min(1).max(120),agentId:z32.uuid().optional()}).strict(),z32.object({kind:z32.literal("system")}).strict()]),NotificationSummarySchema=z32.string().trim().min(1).max(1200),NotificationRunOutcomeSchema=z32.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z32.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z32.discriminatedUnion("topic",[z32.object({topic:z32.literal("agent_question"),questionId:z32.uuid(),title:z32.string().trim().min(1).max(80),description:z32.string().trim().min(1).max(240)}).strict(),z32.object({topic:z32.literal("agent_run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().optional(),proposalId:z32.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema}).strict(),z32.object({topic:z32.literal("agent_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().optional(),summary:NotificationSummarySchema.optional()}).strict()]),NotificationEnvelopeSchema=z32.object({id:z32.uuid(),projectId:z32.uuid(),sourceKey:z32.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z32.literal(1),payload:NotificationPayloadSchema,createdAt:z32.coerce.date()}),NotificationRecipientStateSchema=z32.object({id:z32.uuid(),notificationId:z32.uuid(),projectId:z32.uuid(),userId:z32.string().min(1),readAt:z32.coerce.date().nullable(),archivedAt:z32.coerce.date().nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationDeliveryStateSchema=z32.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z32.object({id:z32.uuid(),notificationRecipientId:z32.uuid(),projectId:z32.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z32.number().int().nonnegative(),nextAttemptAt:z32.coerce.date().nullable(),lastAttemptAt:z32.coerce.date().nullable(),sentAt:z32.coerce.date().nullable(),failureCode:z32.string().max(80).nullable(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),NotificationPreferenceSchema=z32.object({topic:WorkNotificationTopicSchema,channel:z32.literal("email"),enabled:z32.boolean(),source:z32.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z32.object({topics:z32.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("question"),questionId:z32.uuid()}).strict(),z32.object({kind:z32.literal("run_outcome"),threadId:z32.uuid(),invocationId:z32.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z32.object({kind:z32.literal("retained_review"),threadId:z32.uuid(),invocationId:z32.uuid().nullable(),proposalId:z32.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z32.object({kind:z32.literal("merge_conflict"),mergeId:z32.uuid(),threadId:z32.uuid().nullable()}).strict()]),NotificationViewSchema=z32.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z32.object({items:z32.array(NotificationViewSchema),nextCursor:z32.string().nullable(),unreadCount:z32.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z32.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z32.string().min(1).max(120).optional(),sourceKey:z32.string().min(1).max(255).optional(),unread:z32.stringbool().optional(),archived:z32.stringbool().optional(),limit:z32.coerce.number().int().min(1).max(100).optional(),cursor:z32.string().min(1).optional()}).refine(query=>query.actorId===void 0||query.actorKind!==void 0&&query.actorKind!=="system","actorId requires actorKind to be user or agent."),NotificationStateSchema=z32.object({recipient:NotificationRecipientStateSchema,unreadCount:z32.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z32.object({read:z32.boolean().optional(),archived:z32.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z33}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=z33.object({id:z33.uuid(),occurredAt:z33.coerce.date(),projectId:z33.uuid().nullable(),env:z33.string().nullable(),actor:z33.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z33.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z33.unknown().optional(),ipAddress:z33.string().nullable().optional(),userAgent:z33.string().nullable().optional(),error:z33.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z33.object({rows:z33.array(AuditLogRowDTOSchema),nextCursor:z33.string().nullable()})),AuditLogQuerySchema=z33.object({env:z33.string().optional(),action:AuditActionSchema.optional(),actor:z33.string().optional(),from:z33.coerce.date().optional(),to:z33.coerce.date().optional(),limit:z33.coerce.number().int().min(1).max(200).optional(),cursor:z33.string().optional()})}});import{z as z34}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=z34.object({surface:SurfaceNameSchema,key:z34.string(),label:z34.string()}),InlineSchema=z34.object({text:z34.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z34.discriminatedUnion("type",[z34.object({type:z34.literal("paragraph"),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("preview"),ref:DiffRefSchema,caption:z34.string().optional()}),z34.object({type:z34.literal("code"),code:z34.string(),lang:z34.string().optional(),caption:z34.string().optional()}),z34.object({type:z34.literal("risk"),level:z34.enum(["warning","error"]),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("list"),items:z34.array(z34.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z34.object({headline:z34.string(),blocks:z34.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z34.object({summary:EnvDiffSummarySchema,fingerprint:z34.string(),generatedAt:z34.coerce.date(),cached:z34.boolean().optional(),credits:z34.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z35}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=z35.object({date:z35.string(),visitors:z35.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z35.object({key:z35.string(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z35.object({path:z35.string(),pageName:z35.string().nullable().optional(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z35.object({preset:z35.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z35.string(),requestedTo:z35.string(),effectiveFrom:z35.string(),effectiveTo:z35.string(),isRetentionLimited:z35.boolean(),groupBy:z35.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z35.object({date:z35.string(),content:z35.string(),updatedAt:z35.string(),updatedByUserId:z35.string()}),ProjectPageviewAnalyticsDTOSchema=z35.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative(),bounceRate:z35.number().min(0).max(100),viewsPerVisit:z35.number().nonnegative(),averageVisitDurationSeconds:z35.number().nonnegative(),visitorsSeries:z35.array(ProjectDailyVisitorsDTOSchema),topPages:z35.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z35.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z36}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=z36.object({id:z36.string(),email:z36.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z36.coerce.date(),createdAt:z36.coerce.date(),inviterUserId:z36.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z36.object({id:z36.string(),token:z36.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z36.object({success:z36.boolean(),projectId:z36.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z37}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=z37.object({id:z37.string(),name:z37.string(),image:z37.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z37.object({count:z37.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z37.object({counts:z37.object({signed_up:z37.int(),activated:z37.int()}),credits:z37.object({total:z37.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z37.email(),emailVerified:z37.boolean(),createdAt:z37.coerce.date(),updatedAt:z37.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z38}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=z38.object({id:z38.string(),principalType:ProjectPrincipalTypeSchema,principalId:z38.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z38.coerce.date(),expiresAt:z38.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=z38.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z38.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z38.record(z38.string(),z38.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z38.object({access:z38.array(ProjectAccessItemDTOSchema),invites:z38.array(ProjectInviteDTOSchema),organization:z38.object({name:z38.string().nullable(),logo:z38.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z38.object({success:z38.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z38.object({success:z38.boolean(),projectId:z38.uuid()}))}});import{z as z39}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=z39.object({publicationStatus:PublicationStatusSchema,appUrl:z39.string().nullable(),lastPublishedAt:z39.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z40}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z40.object({url:z40.url(),expiresAt:z40.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z40.object({name:z40.string().min(1),locator:z40.string().min(1).optional(),source:z40.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z40.object({kind:z40.literal("dependency_build_scripts_blocked"),packageManager:z40.enum(["pnpm","yarn","bun"]),packages:z40.array(z40.string()),targets:z40.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z40.string(),approvalKey:z40.string(),command:z40.string().optional(),approval:z40.object({id:z40.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z40.object({code:z40.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z40.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z40.object({approvalId:z40.uuid()}),PreviewInstallPolicyApprovalEventSchema=z40.discriminatedUnion("type",[z40.object({type:z40.literal("progress"),step:z40.enum(["approval","install","restart","readiness"]),message:z40.string()}),z40.object({type:z40.literal("approved")}),z40.object({type:z40.literal("complete")}),z40.object({type:z40.literal("error"),code:z40.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z40.string()})])}});import{z as z41}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:z41.string(),slug:z41.string().nullable(),logo:z41.string().nullable(),metadata:z41.record(z41.string(),z41.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z41.object({id:z41.string(),name:z41.string(),email:z41.email(),image:z41.string().nullable()}),OrganizationMemberDTOSchema=z41.object({id:z41.string(),userId:z41.string(),organizationId:z41.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z41.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z42}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z42.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z42.object({reason:CancellationReasonCodeSchema,details:z42.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z42.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z42.object({offerVersion:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),renewsOn:z42.string()}),PlanMigrationPreviewDTOSchema=z42.object({currency:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),startsAt:z42.string(),renewsAt:z42.string(),nextRenewalAmount:z42.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z42.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z42.object({id:z42.string(),organizationId:z42.string(),legacySubscriptionId:z42.string(),offeredPlanCode:z42.string(),offeredPlanName:z42.string(),offeredPriceAmount:z42.number(),offeredCurrency:z42.string(),offerVersion:z42.string(),state:PlanMigrationStateSchema,checkoutToken:z42.string().nullable(),deadlineAt:z42.string(),transitions:z42.array(z42.object({event:z42.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z42.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z42.object({included:z42.number().optional(),unitPrice:z42.number().optional(),dailyCap:z42.number().nullable().optional()}),EntitlementsDTOSchema=z42.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z42.object({retentionDays:z42.number().int().positive(),canUseExtendedDateRanges:z42.boolean()}).optional(),history:z42.object({retentionDays:z42.number().int().positive()}).optional(),members:z42.object({canInvite:z42.boolean(),maxMembers:z42.number().int().positive().nullable()}).optional(),domains:z42.object({canUseCustomDomains:z42.boolean(),maxDomains:z42.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z42.object({id:z42.string(),external_id:z42.string(),customerId:z42.string(),planId:z42.string(),planCode:z42.union([TemplateCodeSchema,z42.literal("Unknown")]),currentPeriod:z42.object({start:z42.string(),end:z42.string().nullable()}),cancelAt:z42.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z42.string(),nextPaymentAt:z42.string().nullable(),baseAmount:z42.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z42.object({totalCap:z42.number(),dailyCap:z42.number(),usedTotal:z42.number()}),CreditBalanceDTOSchema=z42.object({total:z42.number(),base:z42.number(),dailyBase:z42.number(),purchases:z42.number(),awards:z42.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z42.object({total:z42.number(),nearLimit:z42.boolean(),canChat:z42.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z42.object({dailyFreeAvailable:z42.number(),monthlyAvailable:z42.number(),purchasedAvailable:z42.number(),awardedAvailable:z42.number()}),ProjectDailyCreditAllowanceDTOSchema=z42.object({periodCap:z42.number(),dailyGrant:z42.number(),usedThisPeriod:z42.number(),remainingThisPeriod:z42.number()}),ProjectCreditBalanceDTOSchema=z42.object({projectId:z42.uuid(),organizationId:z42.string(),balance:z42.object({totalAvailable:z42.number(),nearLimit:z42.boolean(),canUseAi:z42.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z42.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z42.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z42.object({planCode:z42.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z42.object({source:z42.enum(["cached_subscription","free_fallback"]),settledMs:z42.number().int().nonnegative(),reservedMs:z42.number().int().nonnegative(),includedMs:z42.number().int().positive(),remainingMs:z42.number().int().nonnegative(),resetsAt:z42.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().nonnegative(),refillAmountUsd:z42.number().nonnegative()}),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().nonnegative().nullable(),refillAmountUsd:z42.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().min(.01).multipleOf(.01),refillAmountUsd:z42.number().min(.01).multipleOf(.01)}).strict(),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z42.object({invoiceId:z42.string(),newBalance:z42.int(),creditCount:z42.int(),amountUsd:z42.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z42.object({url:z42.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 z43}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=z43.object({brand:z43.string(),last4:z43.string(),exp:z43.string(),isDefault:z43.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z44}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,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=z44.string().superRefine((path54,ctx)=>{let segments=path54.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=z44.object({type:z44.literal("renameField"),contentType:z44.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z44.object({enabled:z44.boolean()}).strict(),ContentFieldGroupSchema=z44.object({id:z44.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z44.string().min(1).max(255),default:z44.boolean().optional()}).strict(),ContentTypeDTOSchema=z44.object({id:z44.string(),name:z44.string(),label:z44.string(),isSingleton:z44.boolean(),i18n:ContentTypeI18nSchema,groups:z44.array(ContentFieldGroupSchema).default([]),fields:z44.record(z44.string(),FieldDefinitionSchema),createdAt:z44.string(),updatedAt:z44.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z44.object({contentTypes:z44.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z44.object({id:z44.string(),entryId:z44.string(),documentId:z44.string(),slug:z44.string(),locale:z44.string().optional(),createdAt:z44.string(),updatedAt:z44.string(),__fimo:z44.object({contentType:z44.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({limit:z44.number(),offset:z44.number(),total:z44.number(),hasMore:z44.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z44.object({contentType:z44.string(),count:z44.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z44.object({counts:z44.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z44.object({count:z44.number().int().nonnegative(),sourceLocale:z44.string(),targetLocale:z44.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z44.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z44.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z44.union([z44.string(),z44.number(),z44.boolean(),z44.null()]),entryWhereOperatorSchema=z44.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z44.array(entryWhereScalarSchema).optional(),$nin:z44.array(entryWhereScalarSchema).optional(),$contains:z44.string().optional(),$startsWith:z44.string().optional(),$null:z44.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z44.object({data:z44.record(z44.string(),z44.unknown()),locale:z44.string().min(1).optional(),documentId:z44.uuid().optional()}),entryIdsSchema=z44.array(z44.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z44.object({sql:z44.string().min(1)}),BulkCreateEntriesRequestSchema=z44.object({entries:z44.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z44.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z44.object({updates:z44.array(z44.object({id:z44.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,locale:z44.string().min(1).optional()}),z44.object({where:EntryWhereSchema,locale:z44.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z44.object({data:z44.array(z44.record(z44.string(),z44.unknown())),meta:z44.object({rowCount:z44.number().int().nonnegative(),truncated:z44.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({created:z44.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({updated:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({deleted:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z45}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z45.object({index:z45.number().int().nonnegative(),contentType:z45.string(),field:z45.string(),value:z45.string(),against:z45.enum(["stored","batch"]),ownerDocumentId:z45.uuid().optional(),ownerIndex:z45.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z45.object({code:z45.literal("unique_conflict"),message:z45.string(),conflicts:z45.array(UniqueConflictSchema),truncated:z45.boolean().optional()})}});import{z as z46}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=z46.object({kind:z46.literal("unique_conflict"),contentType:z46.string(),field:z46.string(),value:z46.string(),documentCount:z46.number().int().positive(),documentIds:z46.array(z46.uuid()),documentIdsTruncated:z46.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z46.object({code:z46.literal("schema_transition_rejected"),message:z46.string(),issues:z46.array(SchemaTransitionIssueSchema),truncated:z46.boolean().optional()})}});import{z as z47}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=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z47.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z47.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z47.object({field:CmsFieldNameSchema,direction:z47.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z47.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z47.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z47.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z47.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z47.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z48}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=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema))}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}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=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}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=z51.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z51.object({items:z51.array(ProjectMessagePublicDTOSchema),nextCursor:z51.string().nullable()}),ChatLiveTurnDTOSchema=z51.object({invocationId:z51.string(),step:z51.enum(["preparing","working","compacting","merging"]),startedAt:z51.string()}),ChatLiveTurnStateDTOSchema=z51.object({threadId:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z51.object({id:z51.string(),role:z51.enum(["user","assistant"]),parts:z51.array(z51.unknown()),metadata:z51.record(z51.string(),z51.unknown()).nullable(),versionId:z51.string().nullable().optional(),createdAt:z51.date().transform(value=>value.toISOString()),providerMessageId:z51.string().nullable().optional(),invocationId:z51.string().nullable().optional(),invocationStatus:z51.string().nullable().optional(),invocationTerminalReason:z51.string().nullable().optional()}),ChatAttentionDTOSchema=z51.object({type:z51.literal("merge_conflict"),merge:z51.object({mergeId:z51.string().uuid(),projectId:z51.string(),fromEnv:z51.string(),toEnv:z51.string()}),publishAfterMerge:z51.boolean()}),ChatThreadMessagesPageDTOSchema=z51.object({threadId:z51.string().nullable(),title:z51.string().nullable(),messages:z51.array(ChatThreadMessageDTOSchema),nextCursor:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z51.object({kind:z51.literal("replay"),threadId:z51.string(),userMessageId:z51.string()}),ChatQueuedOutcomeDTOSchema=z51.object({kind:z51.literal("queued"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string()}),ChatBusyOutcomeDTOSchema=z51.object({kind:z51.literal("busy"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string().optional()}),ChatRefusedOutcomeDTOSchema=z51.object({kind:z51.literal("refused"),threadId:z51.string(),userMessageId:z51.string(),refusedInvocationId:z51.string(),terminalReason:z51.string()}),ChatNonStreamingOutcomeDTOSchema=z51.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z51.object({success:z51.boolean(),deletedCount:z51.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z51.object({code:z51.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z51.string()})}});import{z as z52}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=z52.object({url:z52.string().url(),key:z52.string(),size:z52.number(),contentType:z52.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z53}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=z53.object({canAccess:z53.boolean(),permissions:z53.record(z53.string(),z53.boolean()),role:z53.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z54}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:z54.string().trim().default(""),sort:z54.enum(["recent","name","relevance"]).default("recent"),category:z54.string().optional()})}});import{z as z55}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=z55.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z55.enum(["fimo","external"]),PaymentStatusSchema=z55.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z55.object({id:z55.string().uuid(),domain:z55.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z55.boolean(),price:z55.number().int().nullable(),renewalPrice:z55.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z55.string().nullable(),failureReason:z55.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z55.object({domain:z55.string(),available:z55.boolean(),premium:z55.boolean(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),purchaseType:z55.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z55.object({domain:z55.string(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),premium:z55.boolean(),allowedYears:z55.array(z55.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z55.object({firstName:z55.string().max(100),lastName:z55.string().max(100),companyName:z55.string().max(100).optional(),address1:z55.string().max(255),address2:z55.string().max(255).optional(),city:z55.string().max(100),state:z55.string().max(100),zip:z55.string().max(20),country:z55.string().max(2),phone:z55.string().max(30),email:z55.union([z55.string().email().max(255),z55.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z55.object({firstName:z55.string().min(1).max(100),lastName:z55.string().min(1).max(100),companyName:z55.string().max(100).optional(),address1:z55.string().min(1).max(255),address2:z55.string().max(255).optional(),city:z55.string().min(1).max(100),state:z55.string().min(1).max(100),zip:z55.string().min(1).max(20),country:z55.string().min(1).max(2),phone:z55.string().min(1).max(30),email:z55.string().email().max(255)}),SearchDomainsRequestSchema=z55.object({keyword:z55.string().min(1).max(100),tldFilter:z55.array(z55.string()).optional()}),CheckAvailabilityRequestSchema=z55.object({domains:z55.array(z55.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=z55.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z55.object({domain:DomainNameSchema,years:z55.number().int().min(1).max(10).optional().default(3),autoRenew:z55.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z55.object({autoRenew:z55.boolean().optional()}),RenewDomainRequestSchema=z55.object({years:z55.number().int().min(1).max(10).optional().default(1),autoRenew:z55.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z55.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z55.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z55.object({verified:z55.boolean(),email:z55.string().nullable(),verifyBy:z55.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z56}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=z56.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=z56.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=z56.object({txtName:z56.string().nullable().optional(),txtValue:z56.string().nullable().optional(),httpUrl:z56.string().nullable().optional(),httpBody:z56.string().nullable().optional(),cname:z56.string().nullable().optional(),cnameTarget:z56.string().nullable().optional()}),SSLValidationErrorSchema=z56.object({message:z56.string()}),OwnershipVerificationSchema=z56.object({type:z56.string(),name:z56.string(),value:z56.string()}),ProjectDomainSSLDTOSchema=z56.object({status:z56.string(),method:z56.string().nullable(),type:z56.string().nullable(),validationRecords:z56.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z56.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z56.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z56.enum(["subdomain","apex"]),RedirectConfigSchema=z56.object({type:z56.literal("apex_to_www"),linkedDomainId:z56.string()}).nullable().optional(),ProjectDomainDTOSchema=z56.object({id:z56.string(),hostname:z56.string(),status:z56.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z56.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z56.string(),scdCnameTarget:z56.string().optional(),apexTargets:z56.array(z56.string()),dnsAutoConfigured:z56.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z56.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z56.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z56.object({hostname:z56.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:z56.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z56.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z56.object({available:z56.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z56.object({success:z56.boolean(),hostname:z56.string()}))}});import{z as z57}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=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z57.object({slug:z57.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z57.object({subdomain:z57.string(),subdomainUpdatedAt:z57.coerce.date()})),SubdomainSuggestionsQuerySchema=z57.object({base:z57.string().max(100).optional(),max:z57.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z57.object({suggestions:z57.array(z57.string())}))}});import{z as z58}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=z58.object({translated:z58.number().int().nonnegative(),total:z58.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z58.object({locale:z58.string(),isDefault:z58.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z58.object({defaultLocale:z58.string(),locales:z58.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z58.object({locale:z58.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z58.object({locale:z58.string().min(1).max(40)}),ProjectLocaleMutationSchema=z58.object({locale:z58.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z58.object({locale:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z59}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=z59.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z59.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=z59.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z59.number(),credits:z59.number().optional(),billingMode:z59.enum(["fimo-credits","provider-account"]).optional(),confidence:z59.enum(["exact","estimated","metered"]),basis:z59.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z60}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=z60.object({options:z60.record(z60.string(),z60.unknown()),name:z60.string().optional(),parentId:z60.string().nullable().optional(),altText:z60.string().optional(),caption:z60.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z60.string().min(1).optional(),model:z60.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=z60.object({jobId:z60.string(),status:z60.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z60.string().nullable().optional(),credits:z60.number().optional(),costUsd:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z60.object({error:z60.string(),code:z60.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:z60.array(GenerationTaskIdSchema).optional(),availableModels:z60.array(z60.string()).optional(),issues:z60.array(z60.unknown()).optional()})}});import{z as z61}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=z61.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z61.object({name:z61.string(),key:z61.string(),description:z61.string(),type:FlagTypeSchema,required:z61.boolean(),defaultValue:z61.unknown().optional(),enumValues:z61.array(z61.string()).optional(),isArray:z61.boolean()}),AssetModelPriceSchema=z61.object({unitPrice:z61.number(),unit:z61.string(),confidence:z61.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z61.object({id:z61.string(),shortName:z61.string(),provider:z61.string(),source:z61.string(),modality:z61.enum(["image","video","audio"]),tags:z61.array(z61.string()),displayName:z61.string(),description:z61.string(),flags:z61.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z61.object({model:z61.string(),costUsd:z61.number(),credits:z61.number(),billingMode:z61.enum(["fimo-credits","provider-account"]),confidence:z61.enum(["exact","estimated","metered"]),basis:z61.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z62}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=z62.object({tourId:z62.string(),version:z62.string(),status:z62.string(),completedAt:z62.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z62.array(UserTourDTOSchema))}});import{z as z63}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=z63.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z63.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z63.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z63.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z63.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z63.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z63.enum(["user","agent","system"]),SupportReportTagSchema=z63.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z63.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z63.object({organization:z63.object({id:z63.string().trim().min(1).max(255),name:z63.string().trim().max(240).optional()}),project:z63.object({id:z63.uuid(),name:z63.string().trim().max(240).optional(),createdAt:z63.coerce.date().optional()}).optional(),environment:z63.string().trim().max(255).optional(),clientVersion:z63.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z63.string().trim().max(200).optional(),limit:z63.coerce.number().int().min(1).max(100).default(50),offset:z63.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z63.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z63.uuid().nullable().optional(),note:z63.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=z63.object({message:z63.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z63.object({kind:SupportReportLinkKindSchema,label:z63.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z63.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z63.object({kind:SupportReportActorKindSchema,id:z63.string().nullable(),name:z63.string().nullable()}),SupportReportLinkDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportLinkKindSchema,label:z63.string(),url:SupportReportHttpUrlSchema,externalId:z63.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportEventKindSchema,body:z63.string().nullable(),metadata:z63.record(z63.string(),z63.unknown()),actor:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z63.object({id:z63.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z63.array(z63.string()),source:SupportReportSourceSchema,message:z63.string(),reporter:z63.object({id:z63.string().nullable(),name:z63.string().nullable(),email:z63.string().nullable()}),organization:z63.object({id:z63.string().nullable(),name:z63.string()}),project:z63.object({id:z63.uuid().nullable(),name:z63.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z63.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z63.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z63.string().nullable(),deliveredAt:z63.coerce.date().nullable()}).nullable(),duplicateOfReportId:z63.uuid().nullable(),resolvedAt:z63.coerce.date().nullable(),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z63.string().nullable(),clientVersion:z63.string().nullable(),links:z63.array(SupportReportLinkDTOSchema),events:z63.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z63.object({reports:z63.array(SupportReportSummaryDTOSchema),total:z63.number().int().nonnegative(),statusCounts:z63.object({new:z63.number().int().nonnegative(),in_progress:z63.number().int().nonnegative(),waiting:z63.number().int().nonnegative(),resolved:z63.number().int().nonnegative(),duplicate:z63.number().int().nonnegative(),irrelevant:z63.number().int().nonnegative(),ignored:z63.number().int().nonnegative()}),limit:z63.number().int().positive(),offset:z63.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z63.object({id:z63.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z63.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z64}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=z64.iso.datetime({offset:!0}).pipe(z64.coerce.date()),OpsRecentChatInputSchema=z64.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z64.string().trim().min(1).max(255).optional(),limit:z64.coerce.number().int().min(1).max(200).default(100),cursor:z64.string().trim().min(1).max(2e3).optional(),slim:z64.boolean().default(!0),reason:z64.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=z64.object({id:z64.string(),threadId:z64.string(),providerMessageId:z64.string().nullable(),invocationId:z64.string().nullable(),env:z64.string().nullable(),role:z64.string(),parts:z64.array(z64.record(z64.string(),z64.unknown())),metadata:z64.object({status:z64.string().optional(),traceUrl:z64.string().optional(),externalFileChanges:z64.array(z64.unknown()).optional()}),stats:z64.object({toolCount:z64.number().int().nonnegative(),failedToolCount:z64.number().int().nonnegative()}),createdAt:z64.iso.datetime({offset:!0}),project:z64.object({id:z64.string(),name:z64.string(),displayName:z64.string().nullable(),organizationId:z64.string().nullable()})}),OpsRecentChatResponseSchema=z64.object({target:z64.object({backendProfile:OpsBackendProfileSchema,projectEnv:z64.string().nullable()}),window:z64.object({from:z64.iso.datetime({offset:!0}),to:z64.iso.datetime({offset:!0})}),messages:z64.object({items:z64.array(OpsRecentChatMessageSchema),nextCursor:z64.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z65}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=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z65.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z65.literal(!1),reason:z65.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z66}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z66.object({packageManager:z66.string().trim().min(1).max(200).nullable(),trackedLockfiles:z66.array(z66.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z66.string().trim().min(1)}),OpsProjectPackageManagerSchema=z66.object({target:z66.object({backendProfile:OpsBackendProfileSchema,projectId:z66.uuid(),projectEnv:z66.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z67}from"zod";function createAgentRunWebhookEventDataSchema(status){return z67.object({run:z67.object({id:z67.string(),agentName:z67.string(),trigger:z67.string(),status:z67.literal(status),startedAt:z67.string().nullable(),finishedAt:z67.string().nullable(),reason:z67.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=z67.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z67.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z67.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z67.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z67.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z67.union([z67.literal(0),z67.literal(5),z67.literal(30),z67.literal(60)]),EntryChangedWebhookEventDataSchema=z67.object({reason:WebhookEntryChangeReasonSchema,operationId:z67.string().optional(),batch:z67.object({index:z67.number().int().positive(),total:z67.number().int().positive()}).optional(),changes:z67.array(z67.object({action:WebhookEntryChangeActionSchema,contentType:z67.string(),id:z67.string(),documentId:z67.string(),locale:z67.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z67.object({form:z67.object({id:z67.string(),label:z67.string()}),submission:z67.object({id:z67.string(),data:z67.record(z67.string(),z67.unknown()),submittedAt:z67.string()})}),PublishStartedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("publishing"),startedAt:z67.string()})}),PublishSucceededWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("published"),url:z67.string(),publishedAt:z67.string(),firstPublish:z67.boolean()})}),PublishFailedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("failed"),reason:z67.string()})}),PublishUnpublishedWebhookEventDataSchema=z67.object({publication:z67.object({previousUrl:z67.string(),unpublishedAt:z67.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),classification:z67.string(),summary:z67.string(),reasons:z67.array(z67.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),resolution:z67.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z67.object({report:z67.object({weekStart:z67.string(),weekEnd:z67.string(),pageviews:z67.number(),visitors:z67.number(),previousPageviews:z67.number(),previousVisitors:z67.number()})}),MediaAssetWebhookEventDataSchema=z67.object({id:z67.string().nullable(),name:z67.string().nullable(),type:z67.string(),mimeType:z67.string().nullable(),fileSize:z67.number().nullable()}),MediaUploadedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["updated","moved","analysis"]),analysis:z67.object({category:z67.string(),status:z67.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("generated"),generation:z67.object({model:z67.string(),mode:z67.string()})}),MediaProcessingFailedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["analysis","generation"]),failure:z67.object({code:z67.string()})}),DomainCreatedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string()})}),LabelChangedWebhookEventDataSchema=z67.object({changes:z67.array(z67.object({action:z67.enum(["created","updated","deleted"]),key:z67.string(),locale:z67.string(),value:z67.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),isDefault:z67.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),previousCode:z67.string()})}),LocaleDeletedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),entriesDeleted:z67.number().int().nonnegative(),labelsDeleted:z67.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z67.object({merge:z67.object({id:z67.string(),from:EnvSchema,to:EnvSchema,applied:z67.array(z67.object({surface:SurfaceNameSchema,count:z67.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z67.object({environment:z67.object({name:EnvSchema}),version:z67.object({versionId:z67.uuid(),name:z67.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=z67.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z67.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z67.discriminatedUnion("source",[z67.object({source:z67.literal("literal"),value:z67.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z67.object({source:z67.literal("secret"),key:z67.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z67.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z67.object({name:z67.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z67.object({name:z67.string(),source:z67.enum(["literal","secret"]),secretKey:z67.string().nullable(),secretPrefix:z67.string().nullable(),configured:z67.literal(!0)}),WebhookFilterSchema=z67.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z67.string().min(1).max(255).optional(),agentName:z67.string().min(1).max(120).optional(),mediaType:z67.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z67.string().min(1).max(255).optional(),locale:z67.string().min(1).max(120).optional()}),JsonValueSchema=z67.lazy(()=>z67.union([z67.string(),z67.number(),z67.boolean(),z67.null(),z67.array(JsonValueSchema),z67.record(z67.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z67.url(),enabled:z67.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z67.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z67.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z67.url().optional(),enabled:z67.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z67.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z67.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z67.object({eventType:WebhookEventTypeSchema.optional(),data:z67.record(z67.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z67.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z67.uuid(),name:z67.string(),eventType:WebhookEventTypeSchema,enabled:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z67.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z67.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z67.coerce.date().nullable(),deliveryStats24h:z67.object({succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z67.uuid(),projectId:z67.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z67.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z67.number().int().positive(),test:z67.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z67.number().int().nonnegative(),responseStatus:z67.number().int().nullable(),lastErrorCode:z67.string().nullable(),lastErrorMessage:z67.string().nullable(),payloadAvailable:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z67.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z67.string().nullable(),qstashMessageId:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z67.object({items:z67.array(WebhookDeliveryDTOSchema),pagination:z67.object({page:z67.number().int().positive(),limit:z67.number().int().positive(),total:z67.number().int().nonnegative(),totalPages:z67.number().int().positive(),hasMore:z67.boolean()}),stats:z67.object({total:z67.number().int().nonnegative(),succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z67.object({id:z67.uuid(),deliveryId:z67.uuid(),attempt:z67.number().int().positive(),status:z67.enum(["delivering","succeeded","failed"]),responseStatus:z67.number().int().nullable(),durationMs:z67.number().int().nonnegative(),responseExcerpt:z67.string().nullable(),errorCode:z67.string().nullable(),errorMessage:z67.string().nullable(),createdAt:z67.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z67.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z67.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z68}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=z68.object({key:z68.literal("fimo-2"),enabled:z68.boolean(),dismissed:z68.boolean().default(!1),interacted:z68.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z69}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=z69.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z69.object({total:z69.number(),base:z69.number(),purchases:z69.number(),awards:z69.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z69.object({id:z69.string(),name:z69.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z69.object({type:z69.string(),brand:z69.string().nullable(),last4:z69.string().nullable(),expirationDate:z69.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z69.object({currency:z69.string(),nextPaymentAmount:z69.number().nullable(),nextPaymentAt:z69.string().nullable(),billingInterval:z69.string().nullable(),totalAmount:z69.number().nullable(),discountAmount:z69.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z69.object({id:z69.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z69.string().nullable(),currentPeriodEndsAt:z69.string().nullable(),renewsAt:z69.string().nullable(),cancelAt:z69.string().nullable(),renewAutomatically:z69.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z69.object({type:z69.enum(["low_balance","critical_balance","approaching_limit"]),message:z69.string(),estimatedPromptsRemaining:z69.number().nullable(),avgCostPerPrompt:z69.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z69.object({monthlyCredits:z69.number().nullable(),usedThisPeriod:z69.number(),remainingThisPeriod:z69.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z69.object({organizationId:z69.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z69.string().nullable(),tenureDays:z69.number().int().nonnegative(),capturedAt:z69.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z69.object({hasSubscription:z69.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z69.number().nullable(),alerts:z69.array(CreditAlertDTOSchema),portalUrl:z69.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z69.object({creditCount:z69.number().int().positive(),expiresAt:z69.string().datetime().nullable().optional(),message:z69.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("free"),amountCents:z69.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("purchase"),amountCents:z69.number().int().positive()}),CreditTopupRequestDTOSchema=z69.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z69.object({success:z69.boolean(),transactionId:z69.string().nullable(),newBalance:z69.number(),creditCount:z69.number(),type:z69.enum(["free","purchase"]),invoiceId:z69.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z70}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=z70.object({totalCredits:z70.number(),totalCostUsd:z70.number(),totalMessages:z70.number(),avgCostPerMessage:z70.number(),periodStart:z70.string().nullable(),periodEnd:z70.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z70.object({date:z70.string(),credits:z70.number(),costUsd:z70.number(),messages:z70.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z70.array(UsageByUserForProjectDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z70.object({summary:UsageSummaryDTOSchema,byProject:z70.array(UsageByProjectDTOSchema),byUser:z70.array(UsageByUserDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z71}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=z71.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z71.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z71.object({startDate:z71.string().optional(),endDate:z71.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z71.coerce.number().int().positive().default(1),limit:z71.coerce.number().int().positive().max(100).default(20),sortBy:z71.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z71.string().optional(),activeOnly:z71.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),avgCreditsPerMessage:z71.number(),periodStart:z71.string(),periodEnd:z71.string(),creditsChange:z71.number().nullable(),costChange:z71.number().nullable(),messagesChange:z71.number().nullable(),unattributedCredits:z71.number(),unattributedCostUsd:z71.number(),unattributedMessages:z71.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z71.object({organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number(),projectCount:z71.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().nullable(),userImage:z71.string().nullable(),organizationId:z71.string().nullable(),organizationName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),projectCount:z71.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z71.object({id:z71.string(),name:z71.string(),value:z71.number(),percentage:z71.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z71.object({day:z71.number(),hour:z71.number(),value:z71.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z71.object({summary:UsageOverviewSummaryDTOSchema,timeline:z71.array(UsageTimelinePointDTOSchema),topOrganizations:z71.array(OrganizationUsageRowDTOSchema),topUsers:z71.array(UserUsageRowDTOSchema),topProjects:z71.array(ProjectUsageRowDTOSchema),creditDistribution:z71.array(UsageDistributionItemDTOSchema),userDistribution:z71.array(UsageDistributionItemDTOSchema),heatmap:z71.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z71.object({page:z71.number(),limit:z71.number(),totalItems:z71.number(),totalPages:z71.number(),hasMore:z71.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z71.object({organizations:z71.array(OrganizationUsageRowDTOSchema),top:z71.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z71.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z71.object({users:z71.array(ExtendedUserUsageRowDTOSchema),top:z71.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z71.object({projects:z71.array(ExtendedProjectUsageRowDTOSchema),top:z71.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z71.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z71.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z71.object({credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),createdAt:z71.string(),memberCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z71.object({id:z71.string(),name:z71.string().nullable(),email:z71.string(),image:z71.string().nullable(),createdAt:z71.string(),organizationCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),displayName:z71.string().nullable(),createdAt:z71.string(),organizationId:z71.string(),organizationName:z71.string(),ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z72}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=z72.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z72.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z72.object({command:z72.string().min(1).max(1e4),cwd:z72.string().optional(),projectEnv:EnvSchema.optional(),env:z72.record(z72.string(),z72.string()).optional(),name:z72.string().optional(),waitForCompletion:z72.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z72.object({identifier:z72.string(),status:SandboxProcessStatusSchema,command:z72.string().optional(),startedAt:z72.string().optional(),exitCode:z72.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z72.object({processes:z72.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z72.object({processId:z72.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z72.object({success:z72.boolean(),message:z72.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z73}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_asset_reading();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_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_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_ops_project_files_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,readFile7=defaultReadFile){try{return JSON.parse(readFile7(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&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function 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:path54,message}=issue;return`${Array.isArray(path54)&&path54.length>0?`${path54.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 SandboxReadinessError,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");SandboxReadinessError=class extends Error{static{__name(this,"SandboxReadinessError")}constructor(message){super(message),this.name="SandboxReadinessError"}},ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path54,status,detail,code2,body){super(`API ${method} ${path54} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path54,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__name(publicationIdFromError,"publicationIdFromError");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}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(path54,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}${path54}`,{...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",path54,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path54,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}${path54}`,{...init,headers})}async rawRequest(path54,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}${path54}`,{...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"} ${path54} 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&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.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,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}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&&params.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 addProjectMcpIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations`,{method:"POST",body:JSON.stringify(input.request)})).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 connectProjectIntegration(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).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&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.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&&params.set("includeDeleted","true"),opts.includeAgentEnvs&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.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,path54,opts={}){let qs=lazyFetchQs(opts.against,{path:path54});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),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path54=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path54}?${qs}`:path54)).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&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.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 getSandboxLogs(projectId,env,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(env)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,env,options={}){let params=new URLSearchParams;options.noRestart&&params.set("noRestart","true"),options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",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="",errorMessage6=null,errorCode,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
43
43
 
44
44
  `);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
45
45
 
@@ -354,7 +354,7 @@ return __eta.res;
354
354
  `)}}return returnStr}function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}function replaceChar(s){return escMap[s]}function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}function escapeRegExp(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
355
355
  `).length}function parse6(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
356
356
  `).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}function render(template,data2,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data2,options)}function renderAsync(template,data2,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data2,options);return Promise.resolve(res)}function renderString(template,data2){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data2)}function renderStringAsync(template,data2){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data2)}function readFile2(path54){let res="";try{res=fs18.readFileSync(path54,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path54}`):err}return res}function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path21.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path21.join(views,formattedPath)}else resolvedFilePath=path21.join(path21.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path21.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}function dirIsChild(parent2,dir){let relative3=path21.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path21.isAbsolute(relative3)}var Cacher,EtaError,EtaParseError,EtaRuntimeError,EtaFileResolutionError,EtaNameResolutionError,AsyncFunction,escMap,defaultConfig2,templateLitReg,singleQuoteReg,doubleQuoteReg,Eta$1,absolutePathRegExp,Eta,init_eta_module=__esm({"../../node_modules/.pnpm/eta@3.5.0/node_modules/eta/dist/eta.module.mjs"(){Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val2){this.cache[key]=val2}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};__name(ParseErr,"ParseErr");__name(RuntimeErr,"RuntimeErr");AsyncFunction=async function(){}.constructor;__name(compile,"compile");__name(compileToString,"compileToString");__name(compileBody,"compileBody");__name(trimWS,"trimWS");escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse6,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse6,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile2,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(path54){try{return JSON.parse(readFileSync4(path54,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, parse${pascal}FormData, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
357
- `)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo-next"},{suffix:".client.ts",runtimeImport:"fimo-next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo-sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(requiredFormEntries,"requiredFormEntries");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z81}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo-next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":"fimo-react"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo-next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo-next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo-sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path54 of schemaFiles){let fileUid=basename(path54,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path54)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path54,"utf-8"))}catch(error){errors.push(`${basename(path54)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path54)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path54)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path54)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path54)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path54)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
357
+ `)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo-next"},{suffix:".client.ts",runtimeImport:"fimo-next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo-sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(requiredFormEntries,"requiredFormEntries");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z81}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?"fimo-next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo-next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo-next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo-sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path54 of schemaFiles){let fileUid=basename(path54,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path54)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path54,"utf-8"))}catch(error){errors.push(`${basename(path54)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path54)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path54)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path54)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path54)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path54)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
358
358
  - ${errors.join(`
359
359
  - `)}
360
360
  No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
@@ -367,7 +367,7 @@ ${imports}
367
367
  export const content = {
368
368
  ${entries2}
369
369
  } as const;
370
- `}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function collectFieldRuntimeTypeImports(field,imports){if(!field||typeof field!="object"||Array.isArray(field))return;let definition=field;switch(definition.type){case"boolean":imports.add("FimoBoolean");return;case"media":imports.add("FimoMedia");return;case"reference":imports.add(Array.isArray(definition.targets)&&definition.targets.length>0?"FimoPolymorphicReference":"FimoReference");return;case"richtext":imports.add("FimoRichText"),imports.add("FimoRichTextContent");return;case"blocks":{let schema=definition.schema;if(!schema||typeof schema!="object"||Array.isArray(schema))return;let blockSchema=schema,fieldGroups=Array.isArray(blockSchema.oneOf)?blockSchema.oneOf.map(variant=>variant&&typeof variant=="object"&&!Array.isArray(variant)?variant.fields:void 0):[blockSchema.fields];for(let fields of fieldGroups)if(!(!fields||typeof fields!="object"||Array.isArray(fields)))for(let nestedField of Object.values(fields))collectFieldRuntimeTypeImports(nestedField,imports);return}default:return}}function runtimeTypeImportsFor(fields){let imports=new Set(["Fields","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"]);for(let field of Object.values(fields))collectFieldRuntimeTypeImports(field,imports);return RUNTIME_TYPE_IMPORT_ORDER.filter(typeImport=>imports.has(typeImport))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields),runtimeTypeImports:runtimeTypeImportsFor(fields)}}function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=contentRuntimeImportFor(options.framework),generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,RUNTIME_TYPE_IMPORT_ORDER,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z81.object({uid:z81.string().min(1),name:z81.string().min(1).optional(),isSingleton:z81.boolean().optional(),i18n:z81.object({enabled:z81.boolean().optional()}).optional(),groups:z81.array(z81.object({id:z81.string().min(1),label:z81.string().min(1),default:z81.boolean().optional()}).strict()).optional(),fields:z81.record(z81.string(),z81.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(readProjectPackage,"readProjectPackage");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(collectFieldRuntimeTypeImports,"collectFieldRuntimeTypeImports");__name(runtimeTypeImportsFor,"runtimeTypeImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
370
+ `}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function collectFieldRuntimeTypeImports(field,imports){if(!field||typeof field!="object"||Array.isArray(field))return;let definition=field;switch(definition.type){case"boolean":imports.add("FimoBoolean");return;case"media":imports.add("FimoMedia");return;case"reference":imports.add(Array.isArray(definition.targets)&&definition.targets.length>0?"FimoPolymorphicReference":"FimoReference");return;case"richtext":imports.add("FimoRichText"),imports.add("FimoRichTextContent");return;case"blocks":{let schema=definition.schema;if(!schema||typeof schema!="object"||Array.isArray(schema))return;let blockSchema=schema,fieldGroups=Array.isArray(blockSchema.oneOf)?blockSchema.oneOf.map(variant=>variant&&typeof variant=="object"&&!Array.isArray(variant)?variant.fields:void 0):[blockSchema.fields];for(let fields of fieldGroups)if(!(!fields||typeof fields!="object"||Array.isArray(fields)))for(let nestedField of Object.values(fields))collectFieldRuntimeTypeImports(nestedField,imports);return}default:return}}function runtimeTypeImportsFor(fields){let imports=new Set(["Fields","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"]);for(let field of Object.values(fields))collectFieldRuntimeTypeImports(field,imports);return RUNTIME_TYPE_IMPORT_ORDER.filter(typeImport=>imports.has(typeImport))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields),runtimeTypeImports:runtimeTypeImportsFor(fields)}}function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=runtime?contentRuntimeImportFor(options.framework,runtime):"fimo-react",generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,RUNTIME_TYPE_IMPORT_ORDER,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z81.object({uid:z81.string().min(1),name:z81.string().min(1).optional(),isSingleton:z81.boolean().optional(),i18n:z81.object({enabled:z81.boolean().optional()}).optional(),groups:z81.array(z81.object({id:z81.string().min(1),label:z81.string().min(1),default:z81.boolean().optional()}).strict()).optional(),fields:z81.record(z81.string(),z81.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(readProjectPackage,"readProjectPackage");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(collectFieldRuntimeTypeImports,"collectFieldRuntimeTypeImports");__name(runtimeTypeImportsFor,"runtimeTypeImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
371
371
  `)}var init_cross_surface=__esm({"src/cli/utils/format/cross-surface.ts"(){__name(renderCrossSurface,"renderCrossSurface")}});function getTerminalWidth(){let w3=process.stdout.columns;return typeof w3=="number"&&w3>0?w3:100}function layoutKeyDetail(args){let{indent,key,keyLength,detail,detailLength=0,width}=args;if(!detail)return`${indent}${key}`;let minGap=args.minGap??2,used=indent.length+keyLength+minGap+detailLength;if(width<80||used>=width)return`${indent}${key}${" ".repeat(minGap)}${detail}`;let padding=width-indent.length-keyLength-detailLength;return`${indent}${key}${" ".repeat(padding)}${detail}`}var init_columns=__esm({"src/cli/utils/format/columns.ts"(){__name(getTerminalWidth,"getTerminalWidth");__name(layoutKeyDetail,"layoutKeyDetail")}});function shortId(id){return id.length>12?`${id.slice(0,8)}\u2026`:id}var assets,init_assets2=__esm({"src/cli/utils/format/surface-presenters/assets.ts"(){assets={label:"ASSETS",hint:"media library",emptyCopy:" (no asset changes)",keyFormatter:__name(item=>item.detail??item.key,"keyFormatter"),detailFormatter:__name(item=>{if(item.detail&&item.key!==item.detail)return shortId(item.key)},"detailFormatter")};__name(shortId,"shortId")}});var code,init_code=__esm({"src/cli/utils/format/surface-presenters/code.ts"(){code={label:"CODE",hint:"git workspace vs HEAD",emptyCopy:" (clean)"}}});var content,init_content=__esm({"src/cli/utils/format/surface-presenters/content.ts"(){content={label:"CONTENT",hint:"entries per collection",emptyCopy:" (no content changes)",groupBy:__name(item=>item.detail??"(unknown)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var forms,init_forms=__esm({"src/cli/utils/format/surface-presenters/forms.ts"(){forms={label:"FORMS",hint:"schema changes",emptyCopy:" (no form changes)"}}});var schemas,init_schemas=__esm({"src/cli/utils/format/surface-presenters/schemas.ts"(){schemas={label:"SCHEMAS",hint:"content types",emptyCopy:" (no schema changes)",groupBy:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(0,idx):""},"groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter")}}});var translations,init_translations=__esm({"src/cli/utils/format/surface-presenters/translations.ts"(){translations={label:"TRANSLATIONS",hint:"per locale",emptyCopy:" (no translation changes)",groupBy:__name(item=>item.detail??"(no locale)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var SURFACE_PRESENTERS,init_surface_presenters=__esm({"src/cli/utils/format/surface-presenters/index.ts"(){init_assets2();init_code();init_content();init_forms();init_schemas();init_translations();SURFACE_PRESENTERS={code,schemas,content,translations,assets,forms}}});function renderItem(item,p2,opts={}){let glyph=VERB_GLYPHS[item.verb]??"?",colored=item.verb==="added"?p2.green(glyph):item.verb==="removed"?p2.red(glyph):item.verb==="conflict"?p2.yellow(glyph):p2.blue(glyph),indent=opts.indent??" ",displayKey=opts.presenter?.keyFormatter?opts.presenter.keyFormatter(item):item.key,displayDetail=opts.presenter?.detailFormatter?opts.presenter.detailFormatter(item):item.detail,width=opts.width;if(item.origin===void 0)return layoutCore({indent,marker:"",markerLen:0,colored,displayKey,displayDetail,width,p:p2});let marker=item.origin==="local-uncommitted"?p2.yellow("*"):" ";return layoutCore({indent,marker,markerLen:1,colored,displayKey,displayDetail,width,p:p2})}function layoutCore(args){let{indent,marker,markerLen,colored,displayKey,displayDetail,width,p:p2}=args,prefix=`${marker}${colored} ${displayKey}`,prefixLen=markerLen+1+1+displayKey.length;return displayDetail?width===void 0?`${indent}${prefix}${p2.dim(` ${displayDetail}`)}`:layoutKeyDetail({indent,key:prefix,keyLength:prefixLen,detail:p2.dim(displayDetail),detailLength:displayDetail.length,width}):`${indent}${prefix}`}function renderSurface(delta,p2,opts={}){let display=SURFACE_DISPLAY[delta.surface],presenter=SURFACE_PRESENTERS[delta.surface],lines=[],includeHeader=opts.includeHeader??!0,maxItems=opts.maxItems??50,width=opts.width??getTerminalWidth();if(includeHeader&&(lines.push(p2.bold(display.label)),lines.push(p2.dim(` ${display.hint}`))),delta.status==="timed_out")return lines.push(p2.yellow(" (surface check timed out)")),lines.join(`
372
372
  `);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
373
373
  `);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
@@ -1418,13 +1418,13 @@ Output
1418
1418
  ${run.output}`:fields},"render")})}__name(renderRunDetail,"renderRunDetail");function renderFields(fields){let width=Math.max(...Object.keys(fields).map(key=>key.length));return Object.entries(fields).map(([key,value])=>`${key.padEnd(width)} ${String(value)}`).join(`
1419
1419
  `)}__name(renderFields,"renderFields");function renderTable(headers,rows){if(rows.length===0)return"No results.";let widths=headers.map((header,index2)=>Math.max(header.length,...rows.map(row2=>String(row2[index2]??"").length)));return[headers,...rows].map(row2=>row2.map((value,index2)=>String(value).padEnd(widths[index2])).join(" ").trimEnd()).join(`
1420
1420
  `)}__name(renderTable,"renderTable");function readActiveRunId(body){if(!body||typeof body!="object")return;let value=body.activeRunId;return typeof value=="string"?value:void 0}__name(readActiveRunId,"readActiveRunId");init_esm();init_dist();import fs49 from"node:fs";import path49 from"node:path";import{isDeepStrictEqual}from"node:util";init_sync_schemas();init_api();init_project_context();init_project();var SYSTEM_SCHEMA_FIELDS=new Set(RESERVED_CONTENT_FIELD_NAMES),SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message,options){super(message,options),this.name="SchemaCommandError",this.code=code2}};function isRecord4(value){return!!(value&&typeof value=="object"&&!Array.isArray(value))}__name(isRecord4,"isRecord");function schemaMatches(actual,expected){if(!isRecord4(actual)||!isRecord4(actual.fields))return!1;let userFields=Object.fromEntries(Object.entries(actual.fields).filter(([fieldName])=>!SYSTEM_SCHEMA_FIELDS.has(fieldName)));return actual.name===expected.name&&actual.label===expected.label&&actual.isSingleton===expected.isSingleton&&isDeepStrictEqual(actual.i18n,expected.i18n)&&isDeepStrictEqual(actual.groups??[],expected.groups)&&isDeepStrictEqual(userFields,expected.fields)}__name(schemaMatches,"schemaMatches");async function readBackSchemaBatch(api,projectId,schemas3){let checks=await Promise.all(schemas3.map(async schema=>{try{let actual=await api.getSchema(projectId,schema.name);return{name:schema.name,actual,state:schemaMatches(actual,schema)?"matched":"mismatched"}}catch(error){if(error instanceof ApiRequestError&&error.status===404)return{name:schema.name,state:"absent"};throw error}})),matched=checks.filter(check=>check.state==="matched"),absent=checks.filter(check=>check.state==="absent"),mismatched=checks.filter(check=>check.state==="mismatched");return matched.length===schemas3.length?{state:"committed",results:matched.map(check=>check.actual)}:absent.length===schemas3.length?{state:"absent"}:{state:"ambiguous",details:[matched.length>0?`matched: ${matched.map(check=>check.name).join(", ")}`:null,absent.length>0?`absent: ${absent.map(check=>check.name).join(", ")}`:null,mismatched.length>0?`mismatched: ${mismatched.map(check=>check.name).join(", ")}`:null].filter(Boolean).join("; ")}}__name(readBackSchemaBatch,"readBackSchemaBatch");async function upsertSchemasWithReconciliation(api,projectId,schemas3,operations){let timeout;try{return await api.upsertSchemas(projectId,schemas3,operations)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let firstReadBack=await readBackAfterTimeout(api,projectId,schemas3,timeout);if(firstReadBack.state==="committed")return firstReadBack.results;if(firstReadBack.state==="ambiguous")throw ambiguousSchemaPushError(firstReadBack.details,timeout);try{return await api.upsertSchemas(projectId,schemas3,operations)}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;timeout=error}let secondReadBack=await readBackAfterTimeout(api,projectId,schemas3,timeout);if(secondReadBack.state==="committed")return secondReadBack.results;let detail=secondReadBack.state==="absent"?"all requested schemas remain absent after one retry":secondReadBack.details;throw ambiguousSchemaPushError(detail,timeout)}__name(upsertSchemasWithReconciliation,"upsertSchemasWithReconciliation");function ambiguousSchemaPushError(detail,cause){return new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 (${detail}). No further write was attempted; read the schemas back before rerunning.`,{cause})}__name(ambiguousSchemaPushError,"ambiguousSchemaPushError");async function readBackAfterTimeout(api,projectId,schemas3,timeout){try{return await readBackSchemaBatch(api,projectId,schemas3)}catch(error){let detail=error instanceof Error?error.message:String(error);throw new SchemaCommandError("SCHEMA_PUSH_AMBIGUOUS",`Schema push returned an ambiguous 504 and read-back failed (${detail}). No retry was attempted.`,{cause:timeout})}}__name(readBackAfterTimeout,"readBackAfterTimeout");function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},groups:schema.groups??[],fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson8,"renderPrettyJson");function isUniqueConflictIssue(issue){if(!issue||typeof issue!="object"||Array.isArray(issue))return!1;let candidate=issue;return candidate.kind==="unique_conflict"&&typeof candidate.contentType=="string"&&typeof candidate.field=="string"&&typeof candidate.value=="string"&&typeof candidate.documentCount=="number"&&Array.isArray(candidate.documentIds)&&candidate.documentIds.every(id=>typeof id=="string")&&(candidate.documentIdsTruncated===void 0||typeof candidate.documentIdsTruncated=="boolean")}__name(isUniqueConflictIssue,"isUniqueConflictIssue");function getUniqueConflictIssues(body){if(!body||typeof body!="object"||Array.isArray(body))return null;let issues=body.issues;return Array.isArray(issues)?issues.filter(isUniqueConflictIssue):null}__name(getUniqueConflictIssues,"getUniqueConflictIssues");function renderSchemaTransitionRejected(body,issues){currentMode().format==="json"?ui.result({command:"schemas push",data:body,render:__name(()=>"","render")}):ui.table({command:"schemas push",headline:"Schema push rejected. Nothing was written.",columns:[{key:"content_type",label:"CONTENT TYPE"},{key:"field",label:"FIELD"},{key:"value",label:"VALUE"},{key:"documents",label:"DOCUMENTS"},{key:"document_ids",label:"DOCUMENT IDS"}],rows:issues.map(issue=>{let remaining=Math.max(issue.documentCount-issue.documentIds.length,0),truncationNote=remaining>0?`... and ${remaining} more`:"... and more";return{content_type:issue.contentType,field:issue.field,value:issue.value,documents:issue.documentCount,document_ids:issue.documentIdsTruncated?[...issue.documentIds,truncationNote].join(", "):issue.documentIds.join(", ")}})}),process.exitCode=1}__name(renderSchemaTransitionRejected,"renderSchemaTransitionRejected");async function schemaListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listSchemas(ctx.projectId);ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSchema(ctx.projectId,typeName);ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),schemasDir=path49.join(cwd,"src/schemas"),allSchemaFiles=fs49.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs49.readFileSync(path49.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files.map(file=>{let filePath=path49.join(schemasDir,file);if(!fs49.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path49.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue=>`${issue.file}: ${issue.message}`).join(`
1421
- `));return JSON.parse(fs49.readFileSync(filePath,"utf-8"))}),framework=await detectProjectFramework(cwd);syncSchemas({cwd,framework:framework?.slug??null,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await upsertSchemasWithReconciliation(api,ctx.projectId,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_dist();init_project_context();var SinglesInputError=class extends Error{static{__name(this,"SinglesInputError")}constructor(message){super(message),this.name="SinglesInputError"}};function renderPrettyJson9(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson9,"renderPrettyJson");function parseJsonObject2(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new SinglesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new SinglesInputError("Expected a JSON object.");return parsed}__name(parseJsonObject2,"parseJsonObject");async function singlesGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSingle(ctx.projectId,typeName,{locale:options.locale,populate:options.populate});ui.result({command:"singles get",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesGetCommand,"singlesGetCommand");async function singlesUpdateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,env:ctx.env});let body=parseJsonObject2(await readContentInputSource(options,message=>new SinglesInputError(message))),result=await api.updateSingle(ctx.projectId,typeName,options.locale,body);ui.result({command:"singles update",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesUpdateCommand,"singlesUpdateCommand");init_skills();init_status();init_dist5();init_dist();init_api();init_config();init_auth_errors();init_interactive();init_project_context();init_version();import{readFileSync as readFileSync11}from"node:fs";import path50 from"node:path";var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with project and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Project directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addHelpText("after",`
1421
+ `));return JSON.parse(fs49.readFileSync(filePath,"utf-8"))}),framework=await detectProjectFramework(cwd);syncSchemas({cwd,framework:framework?.slug??null,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await upsertSchemasWithReconciliation(api,ctx.projectId,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_dist();init_project_context();var SinglesInputError=class extends Error{static{__name(this,"SinglesInputError")}constructor(message){super(message),this.name="SinglesInputError"}};function renderPrettyJson9(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson9,"renderPrettyJson");function parseJsonObject2(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new SinglesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new SinglesInputError("Expected a JSON object.");return parsed}__name(parseJsonObject2,"parseJsonObject");async function singlesGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSingle(ctx.projectId,typeName,{locale:options.locale,populate:options.populate});ui.result({command:"singles get",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesGetCommand,"singlesGetCommand");async function singlesUpdateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,env:ctx.env});let body=parseJsonObject2(await readContentInputSource(options,message=>new SinglesInputError(message))),result=await api.updateSingle(ctx.projectId,typeName,options.locale,body);ui.result({command:"singles update",data:result,render:__name(()=>renderPrettyJson9(result),"render")})}__name(singlesUpdateCommand,"singlesUpdateCommand");init_skills();init_status();init_dist5();init_dist();import{readFileSync as readFileSync11}from"node:fs";import path50 from"node:path";init_api();init_config();init_auth_errors();init_interactive();init_project_context();init_version();var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with project and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Project directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addOption(new Option("--source <origin>","Origin of the report").choices(["agent"]).hideHelp()).addHelpText("after",`
1422
1422
  Examples:
1423
1423
  fimo support report "Preview deployment fails after validation"
1424
1424
  fimo support report --message-file /tmp/fimo-support-report.md --preview --json
1425
1425
  fimo support report --message-file /tmp/fimo-support-report.md --yes --json
1426
1426
 
1427
- `).action((message,options,command)=>supportReportCommand(message??[],options,command))}__name(registerSupportCommands,"registerSupportCommands");async function supportReportCommand(messageParts,options,command){let message=resolveSupportMessage(messageParts,options.messageFile);if(message===null)return;let cfg=loadConfig(),api=new FimoApiClient(cfg),projectContext=await getProjectContext({cwd:options.cwd,envOverride:envOverrideFromCommand(command)});try{let[project,organizations]=await Promise.all([api.getProject(projectContext.projectId),api.listOrganizations()]),organizationId=project.organizationId??projectContext.organizationId,organization=organizations.find(candidate=>candidate.id===organizationId),reportContext={message,projectId:project.id,projectName:project.displayName??project.name,organizationId,organizationName:organization?.name??organizationId,environment:projectContext.env,cliVersion:getCliVersion()},submittedMessage=buildSupportMessage(reportContext);if(submittedMessage.length>MAX_SUPPORT_MESSAGE_LENGTH){ui.error({command:"support report",code:"SUPPORT_MESSAGE_TOO_LONG",message:`The complete report is ${submittedMessage.length.toLocaleString()} characters; the limit is ${MAX_SUPPORT_MESSAGE_LENGTH.toLocaleString()}.`,hint:"Keep the observed failure or capability gap, impact, and workaround; remove raw logs and unrelated context."});return}if(options.preview){ui.result({command:"support report",data:{submitted:!1,message:submittedMessage,project_id:reportContext.projectId,project_name:reportContext.projectName,environment:reportContext.environment},render:__name(()=>submittedMessage,"render")});return}if(!options.yes){assertInteractive("Review the report, then pass --yes to send it without prompting.","support report"),wt(submittedMessage,"Report preview");let confirmed=await ot2({message:"Send this report to Fimo support?",initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"support report",message:"Cancelled."});return}}let result=await api.submitSupportIssue({message:submittedMessage,category:"project_issues",context:{organization:{id:reportContext.organizationId,name:reportContext.organizationName},project:{id:reportContext.projectId,name:reportContext.projectName,createdAt:new Date(project.createdAt)},environment:reportContext.environment,clientVersion:reportContext.cliVersion}});ui.result({command:"support report",data:{submitted:!0,project_id:reportContext.projectId,project_name:reportContext.projectName,environment:reportContext.environment,report_id:result.id,delivery_status:result.deliveryStatus},render:__name(()=>`${result.message}
1427
+ `).action((message,options,command)=>supportReportCommand(message??[],options,command))}__name(registerSupportCommands,"registerSupportCommands");async function supportReportCommand(messageParts,options,command){let message=resolveSupportMessage(messageParts,options.messageFile);if(message===null)return;let cfg=loadConfig(),api=new FimoApiClient(cfg),projectContext=await getProjectContext({cwd:options.cwd,envOverride:envOverrideFromCommand(command)});try{let[project,organizations]=await Promise.all([api.getProject(projectContext.projectId),api.listOrganizations()]),organizationId=project.organizationId??projectContext.organizationId,organization=organizations.find(candidate=>candidate.id===organizationId),reportContext={message,projectId:project.id,projectName:project.displayName??project.name,organizationId,organizationName:organization?.name??organizationId,environment:projectContext.env,cliVersion:getCliVersion()},submittedMessage=buildSupportMessage(reportContext);if(submittedMessage.length>MAX_SUPPORT_MESSAGE_LENGTH){ui.error({command:"support report",code:"SUPPORT_MESSAGE_TOO_LONG",message:`The complete report is ${submittedMessage.length.toLocaleString()} characters; the limit is ${MAX_SUPPORT_MESSAGE_LENGTH.toLocaleString()}.`,hint:"Keep the observed failure or capability gap, impact, and workaround; remove raw logs and unrelated context."});return}if(options.preview){ui.result({command:"support report",data:{submitted:!1,message:submittedMessage,project_id:reportContext.projectId,project_name:reportContext.projectName,environment:reportContext.environment},render:__name(()=>submittedMessage,"render")});return}if(!options.yes){assertInteractive("Review the report, then pass --yes to send it without prompting.","support report"),wt(submittedMessage,"Report preview");let confirmed=await ot2({message:"Send this report to Fimo support?",initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"support report",message:"Cancelled."});return}}let result=await api.submitSupportIssue({message:submittedMessage,category:"project_issues",source:options.source??"cli",context:{organization:{id:reportContext.organizationId,name:reportContext.organizationName},project:{id:reportContext.projectId,name:reportContext.projectName,createdAt:new Date(project.createdAt)},environment:reportContext.environment,clientVersion:reportContext.cliVersion}});ui.result({command:"support report",data:{submitted:!0,project_id:reportContext.projectId,project_name:reportContext.projectName,environment:reportContext.environment,report_id:result.id,delivery_status:result.deliveryStatus},render:__name(()=>`${result.message}
1428
1428
  Report: ${result.id}
1429
1429
  Project: ${reportContext.projectName}
1430
1430
  Environment: ${reportContext.environment}`,"render")})}catch(error){rethrowCliAuthError(error),ui.error({command:"support report",code:"SUPPORT_REPORT_FAILED",message:error instanceof Error?error.message:"The support report could not be sent.",hint:"Try again later, or contact Fimo support through the app."})}}__name(supportReportCommand,"supportReportCommand");function resolveSupportMessage(messageParts,messageFile){if(messageParts.length>0&&messageFile)return ui.error({command:"support report",code:"SUPPORT_MESSAGE_CONFLICT",message:"Pass the report as text or with --message-file, not both."}),null;let message=messageParts.join(" ").trim();if(messageFile)try{message=readFileSync11(path50.resolve(messageFile),"utf8").trim()}catch(error){return ui.error({command:"support report",code:"SUPPORT_MESSAGE_READ_FAILED",message:error instanceof Error?error.message:"The report file could not be read."}),null}return message||(ui.error({command:"support report",code:"SUPPORT_MESSAGE_REQUIRED",message:"Describe what went wrong or which capability is missing, or pass --message-file <path>."}),null)}__name(resolveSupportMessage,"resolveSupportMessage");function buildSupportMessage(context){return[context.message,"","Fimo CLI context",`Project: ${context.projectName} (${context.projectId})`,`Environment: ${context.environment}`,`Fimo CLI: ${context.cliVersion}`].join(`