fimo 2.2.0-staging.12 → 2.2.0-staging.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/content-templates/shared/types.eta +65 -6
- package/assets/skills/fimo-code/references/assets.md +22 -11
- package/assets/skills/fimo-code/references/content/clients.md +15 -1
- package/assets/skills/fimo-migration/SKILL.md +10 -3
- package/assets/skills/fimo-migration/references/media.md +11 -0
- package/assets/skills/fimo-migration/references/workflow.md +3 -0
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +39 -25
- package/dist/runtime/content/serialization.d.ts +4 -3
- package/dist/runtime/content/serialization.js +4 -3
- package/dist/runtime/primitives/lib/primitives.d.ts +15 -7
- package/dist/runtime/primitives/lib/primitives.js +14 -1
- package/package.json +7 -7
- package/templates/astro/package.json +2 -2
- package/templates/nextjs/package.json +3 -3
- package/templates/react-router/package.json +4 -4
- package/templates/sveltekit/package.json +2 -2
- package/templates/vite/package.json +4 -4
package/dist/cli/index.js
CHANGED
|
@@ -39,16 +39,16 @@ 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=path53.basename(filename,path53.extname(filename)),this}executableDir(path54){return path54===void 0?this._executableDir:(this._executableDir=path54,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,createPaginatedResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema"),createPaginatedResponseSchema=__name(dataSchema=>z2.object({data:z2.array(dataSchema),page:z2.number(),total:z2.number(),totalPages:z2.number(),hasMore:z2.boolean()}),"createPaginatedResponseSchema");__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 isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function branchResourceKey(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${branchResourceKey(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment,"encodeBranchPathSegment");BranchSchema=z7.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});import{z as 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:BranchSchema,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,path53){let conditionPath=[...path53,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path53)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path53));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path53,fieldName,variant.uid]);else walk(field.schema.fields,[...path53,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path53,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path53,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_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_entitlements_sync","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,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,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"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),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"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),OpsAgentTraceStatsGroupBySchema=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)}),OpsBillingEntitlementSyncInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50),concurrency:z13.number().int().min(1).max(10).default(2)}),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";function derivedBlockBody(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"series":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"findings":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"image":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
|
|
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,createPaginatedResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema"),createPaginatedResponseSchema=__name(dataSchema=>z2.object({data:z2.array(dataSchema),page:z2.number(),total:z2.number(),totalPages:z2.number(),hasMore:z2.boolean()}),"createPaginatedResponseSchema");__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 isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function branchResourceKey(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${branchResourceKey(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment,"encodeBranchPathSegment");BranchSchema=z7.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});import{z as 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:BranchSchema,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,path53){let conditionPath=[...path53,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path53)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path53));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path53,fieldName,variant.uid]);else walk(field.schema.fields,[...path53,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path53,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path53,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_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_entitlements_sync","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,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,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"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),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"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),OpsAgentTraceStatsGroupBySchema=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)}),OpsBillingEntitlementSyncInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50),concurrency:z13.number().int().min(1).max(10).default(2)}),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";function normalizeStoredBlock(block){if(typeof block!="object"||block===null||Array.isArray(block))return block;let{type,...rest}=block;if(typeof type!="string")return block;let target=LEGACY_BLOCK_TYPES[type];return target?target==="viz"?{...rest,type:target,kind:"bar"}:{...rest,type:target}:block}function normalizeStoredBlocks(blocks){return Array.isArray(blocks)?blocks.map(normalizeStoredBlock):blocks}function normalizeStoredDocument(document){if(typeof document!="object"||document===null||Array.isArray(document))return document;let source=document;return{...source,brief:normalizeStoredBlocks(source.brief),details:normalizeStoredBlocks(source.details)}}function normalizeReportDocument(document){return document==null?null:StoredReportDocumentSchema.parse(document)}function derivedBlockBody(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"viz":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"list":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"media":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
|
|
43
43
|
`)}function reportSectionContentLength(blocks){return blocks.reduce((total,block)=>total+(block.title?.length??0)+derivedBlockBody(block).length+(block.fallback?.length??0),0)}function reportBlockMarkdown(block){let parts=[];switch(block.title&&parts.push(`## ${block.title}`),block.type){case"text":parts.push(block.text);break;case"metric":parts.push(block.items.map(item=>[`**${item.value}${item.unit??""}** \u2014 ${item.label}`,item.note].filter(Boolean).join(`
|
|
44
44
|
`)).join(`
|
|
45
45
|
|
|
46
|
-
`));break;case"
|
|
47
|
-
`)),block.caption&&parts.push(block.caption);break;case"
|
|
46
|
+
`));break;case"viz":parts.push(block.points.map(point=>`- ${point.label}: ${formatReportValue(point.value,block.unit)}`).join(`
|
|
47
|
+
`)),block.caption&&parts.push(block.caption);break;case"list":parts.push(block.items.map(item=>[`**${[item.label,item.heading].filter(Boolean).join(" \u2014 ")}**`,item.body,item.evidence].filter(Boolean).join(`
|
|
48
48
|
`)).join(`
|
|
49
49
|
|
|
50
50
|
`));break;case"table":parts.push([`| ${block.columns.map(column=>escapeCell(column.label)).join(" | ")} |`,`| ${block.columns.map(()=>"---").join(" | ")} |`,...block.rows.map(row2=>`| ${row2.cells.map(cell=>escapeCell(cell.text)).join(" | ")} |`)].join(`
|
|
51
|
-
`)),block.caption&&parts.push(block.caption);break;case"
|
|
51
|
+
`)),block.caption&&parts.push(block.caption);break;case"media":parts.push([`_${block.alt}_`,block.caption].filter(Boolean).join(`
|
|
52
52
|
|
|
53
53
|
`));break;case"links":parts.push(block.items.map(item=>`- [${escapeCell(item.label)}](${item.url})${item.description?` \u2014 ${item.description}`:""}`).join(`
|
|
54
54
|
`));break;case"code":parts.push(`\`\`\`${block.language??""}
|
|
@@ -57,14 +57,14 @@ ${block.code}
|
|
|
57
57
|
|
|
58
58
|
`)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&§ions.push(...document.details.map(reportBlockMarkdown)),sections.join(`
|
|
59
59
|
|
|
60
|
-
`)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),ReportSeriesBlockSchema=z15.object({type:z15.literal("series"),...blockCommon,unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."})}),ReportFindingsBlockSchema=z15.object({type:z15.literal("findings"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema,label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Several ranked problems, risks, or recommendations. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index2)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportImageBlockSchema=z15.object({type:z15.literal("image"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual evidence or a visual deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportSeriesBlockSchema,ReportFindingsBlockSchema,ReportTableBlockSchema,ReportImageBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z16}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=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.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:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.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(path53){return[...path53.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path53){return pageRouteParamNames(path53).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 z17}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=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),previewEnabled:z17.boolean().default(!0),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),snapshotUrl:z17.string().startsWith("/").optional(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}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=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}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=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}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=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}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=z22.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z22.object({type:z22.literal("manual")}),ScheduleTriggerSchema=z22.object({type:z22.literal("schedule"),cron:z22.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:z22.string().optional()}),WebhookTriggerSchema=z22.object({type:z22.literal("webhook"),path:z22.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z22.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z23}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=z23.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z23.object({token:z23.string().min(1),risk:CapabilityRiskTierSchema,description:z23.string()}),AgentSubAgentSummarySchema=z23.object({name:z23.string().min(1),grant:z23.enum(["inherit","explicit"]),effectiveCaps:z23.array(z23.string().min(1))}),AgentInstallSummaryDTOSchema=z23.object({agentName:z23.string().min(1),env:z23.string().min(1),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z23.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z23.array(CapabilitySummaryEntrySchema),criticalCapabilities:z23.array(CapabilitySummaryEntrySchema),subAgents:z23.array(AgentSubAgentSummarySchema),declaresDelegate:z23.boolean(),cycle:z23.array(z23.string()).nullable(),missingSubAgents:z23.array(z23.string()),warnings:z23.array(z23.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z24}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=z24.object({kind:TriggerKindSchema,summary:z24.string()}),AgentListItemTriggerStateSchema=z24.object({triggerIndex:z24.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z24.boolean(),wired:z24.boolean(),syncError:z24.string().nullable()}),AgentListItemDTOSchema=z24.object({name:z24.string().min(1),description:z24.string().nullable(),goalFirstLine:z24.string().nullable(),declaredCapabilities:z24.array(CapabilitySummaryEntrySchema),triggers:z24.array(AgentListItemTriggerSchema),triggerStates:z24.array(AgentListItemTriggerStateSchema),paused:z24.boolean(),nextRunAt:z24.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z24.array(AgentListItemDTOSchema))}});import{z as z25}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z25.object({paused:z25.boolean(),cancelledRuns:z25.number().int().nonnegative(),stopIncomplete:z25.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema(AgentControlResultSchema)}});import{z as z26}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=z26.object({args:z26.unknown().optional(),requestId:z26.string().min(1).max(128).optional()}),DispatchSkippedSchema=z26.object({skipped:z26.enum(["no-manual-trigger","trigger-not-wired","agent-paused","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z26.object({sessionId:z26.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z26.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z27}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=z27.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z27.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z27.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z27.object({verb:SurfaceDeltaVerbSchema,key:z27.string(),detail:z27.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z27.record(z27.string(),z27.unknown()).optional()}),PerSurfaceDeltaSchema=z27.object({surface:SurfaceNameSchema,status:z27.enum(["ok","timed_out","failed","unchanged"]),durationMs:z27.number().int().nonnegative().optional(),changedCount:z27.number().int().nonnegative(),conflictCount:z27.number().int().nonnegative(),items:z27.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z27.boolean().optional(),error:z27.string().optional()}),CrossSurfaceFindingSchema=z27.object({id:z27.string(),kind:z27.string(),description:z27.string(),severity:z27.enum(["warning","error"]),source:z27.object({surface:SurfaceNameSchema,key:z27.string()}),target:z27.object({surface:SurfaceNameSchema,key:z27.string()}),actions:z27.array(z27.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z27.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z27.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),agents:z27.array(z27.object({id:z27.string(),name:z27.string(),status:z27.enum(["active","paused","failed"]),lastRunAt:z27.coerce.date().nullable()})).optional(),crossSurface:z27.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z27.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),crossSurface:z27.array(CrossSurfaceFindingSchema).optional(),fingerprint:z27.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z27.object({path:z27.string(),state:z27.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z27.string(),additions:z27.number().int().nonnegative(),deletions:z27.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z27.object({oid:z27.string().optional(),content:z27.string().optional(),truncated:z27.boolean(),binary:z27.boolean()}),CodeConflictDetailSchema=z27.object({path:z27.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z27.string(),targetTipSha:z27.string(),mergeBaseSha:z27.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z27.object({id:z27.string(),slug:z27.string(),contentType:z27.string(),data:z27.record(z27.string(),z27.unknown()),updatedAt:z27.coerce.date()}),ContentRowDiffSchema=z27.object({collection:z27.string(),rowId:z27.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z27.object({name:z27.string(),label:z27.string(),isSingleton:z27.boolean(),fields:z27.record(z27.string(),z27.unknown())}),SchemaTypeDiffSchema=z27.object({typeName:z27.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z27.object({id:z27.string(),name:z27.string(),type:z27.enum(["file","folder"]),mimeType:z27.string().nullable(),storageKey:z27.string().nullable(),url:z27.string().nullable(),fileSize:z27.number().nullable(),width:z27.number().nullable(),height:z27.number().nullable(),altText:z27.string().nullable(),caption:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AssetDiffSchema=z27.object({assetId:z27.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z27.object({locale:z27.string(),key:z27.string(),parent:z27.string().nullable(),child:z27.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z27.object({formName:z27.string(),label:z27.string().nullable(),schemaFingerprint:z27.string(),fields:z27.record(z27.string(),z27.unknown()),settings:z27.record(z27.string(),z27.unknown()).optional()}),FormSchemaDiffSchema=z27.object({formName:z27.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=z27.enum(CONFLICT_KINDS),ConflictSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),kind:ConflictKindSchema.optional(),description:z27.string(),parentValue:z27.unknown().optional(),childValue:z27.unknown().optional(),conflictingFields:z27.array(z27.string()).optional(),code:z27.object({path:z27.string(),unresolvable:z27.boolean().optional(),reason:z27.string().optional()}).optional()}),FieldPickSchema=z27.object({field:z27.string(),choice:z27.enum(["parent","child","pick","ai-pick"]),pickedValue:z27.unknown().optional(),aiSessionId:z27.string().optional()}),ConflictResolutionSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),choice:z27.enum(["parent","child","pick"]),pickedValue:z27.unknown().optional(),fieldPicks:z27.array(FieldPickSchema).optional()}),MergeResultSchema=z27.object({ok:z27.boolean(),mergeId:z27.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z27.array(z27.object({surface:SurfaceNameSchema,count:z27.number().int().nonnegative()})),conflicts:z27.array(ConflictSchema).optional(),summary:z27.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z27.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z27.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z27.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z27.boolean().optional()}),ResolvedStrategySchema=z27.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z27.boolean()}),MergeRequestSchema=z27.object({from:BranchSchema,allowDirectMerge:z27.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z27.object({mergeId:z27.string().uuid(),streamUrl:z27.string(),strategy:ResolvedStrategySchema,acceptedAt:z27.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z27.object({mergeId:z27.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z27.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z27.array(ConflictSchema),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedBy:z27.string().nullable(),lastEditedAt:z27.coerce.date().nullable(),initiator:z27.object({userId:z27.string().nullable(),role:z27.string().nullable(),agentName:z27.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z27.object({resolutions:z27.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z27.object({mergeId:z27.string().uuid(),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedAt:z27.coerce.date(),lastEditedBy:z27.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z27.object({mergeId:z27.string().uuid(),resolutions:z27.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z27.object({mergeId:z27.string().uuid()}),PublishReleaseRequestSchema=z27.object({version:z27.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z27.string().max(2e4).optional()}),PublishReleaseResultSchema=z27.object({releaseTag:z27.string(),sha:z27.string(),publishedAt:z27.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z28}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z28.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z28.enum(["in-progress","done","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z28.object({env:z28.string().optional(),project_agents_only:z28.coerce.boolean().optional(),agent_name:z28.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z28.coerce.date().optional(),page:z28.coerce.number().int().positive().default(1),limit:z28.coerce.number().int().positive().max(200).default(25),cursor:z28.coerce.date().optional()}),SessionMetricsSchema=z28.object({cpuMs:z28.number().nonnegative().default(0),netBytes:z28.number().nonnegative().default(0),walltimeMs:z28.number().nonnegative().default(0),llmTokensIn:z28.number().nonnegative().optional(),llmTokensOut:z28.number().nonnegative().optional(),stepCount:z28.number().int().nonnegative().optional(),toolCallCounts:z28.record(z28.string().min(1).max(120),z28.number().int().nonnegative()).optional(),toolCallOutcomes:z28.array(z28.object({toolName:z28.string().min(1).max(120),success:z28.boolean(),code:z28.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z28.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z28.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z28.object({capturedAt:z28.coerce.date(),fingerprint:z28.string().min(1).max(256),counts:z28.object({code:z28.number().int().nonnegative(),content:z28.number().int().nonnegative(),schemas:z28.number().int().nonnegative(),labels:z28.number().int().nonnegative(),assets:z28.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z28.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z28.object({diff:DiffReportSchema,code:z28.array(CodeFileDiffSchema.extend({raw:z28.string().max(24576)})).max(200),schemas:z28.array(SchemaTypeDiffSchema).max(200),content:z28.array(z28.object({key:z28.string().min(1).max(512),collection:z28.string().min(1).max(256),slug:z28.string().max(512).optional(),verb:z28.enum(["added","modified","deleted"]),fields:z28.array(z28.object({name:z28.string().min(1).max(256),before:z28.unknown().optional(),after:z28.unknown().optional()})).max(20)})).max(200),labels:z28.array(z28.object({key:z28.string().min(1).max(512),locale:z28.string().min(1).max(64).optional(),before:z28.unknown().nullable(),after:z28.unknown().nullable()})).max(200),assets:z28.array(z28.object({key:z28.string().min(1).max(512),name:z28.string().min(1).max(512),verb:z28.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z28.object({id:z28.uuid(),projectId:z28.uuid(),env:BranchSchema,agentName:z28.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z28.unknown().optional(),capabilities:z28.array(z28.string()).optional(),dataSources:z28.array(z28.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z28.string().nullable(),startedAt:z28.coerce.date().nullable(),finishedAt:z28.coerce.date().nullable(),cancelledAt:z28.coerce.date().nullable(),costUsd:z28.number().nonnegative(),costCeilingUsd:z28.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z28.boolean(),lastCheckpointId:z28.uuid().nullable(),branchEnvId:z28.uuid().nullable(),parentSessionId:z28.uuid().nullable(),terminalReason:z28.string().nullable(),errorMessage:z28.string().nullable(),reportDocument:ReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z28.string().nullable(),createdAt:z28.coerce.date(),updatedAt:z28.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z28.object({id:z28.uuid(),sessionId:z28.uuid(),checkpointIdx:z28.number().int().nonnegative(),payloadRef:z28.string(),payloadSizeBytes:z28.number().int().nonnegative(),checksum:z28.string().length(64),createdAt:z28.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z28.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z28.object({session:AgentSessionDTOSchema,checkpoints:z28.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z28.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=z28.object({reason:z28.string().min(1).max(120).optional()})}});import{z as z29}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=z29.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z29.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z29.object({id:z29.uuid(),envId:z29.uuid(),sessionId:z29.uuid().nullable(),skillName:z29.string().min(1),classification:AgentBranchClassificationSchema,rationale:z29.string().nullable(),summary:z29.string().nullable(),surfaceDeltas:z29.record(z29.string(),z29.unknown()),createdAt:z29.coerce.date(),decidedAt:z29.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z29.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z29.object({path:z29.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z29.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z29.object({code:z29.literal("merge_conflict"),message:z29.string(),conflicts:z29.record(z29.string(),z29.number().int().nonnegative())})}});import{z as z30}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=z30.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z30.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=z30.object({description:z30.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z30.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),threadId:z30.uuid(),invocationId:z30.uuid(),agentKey:z30.string().min(1).max(120),anchorEnv:z30.string().min(1).max(64),retainedEnv:z30.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z30.string().min(1).nullable(),continuationInvocationId:z30.uuid().nullable(),askedAt:z30.coerce.date(),expiresAt:z30.coerce.date(),closedAt:z30.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z30.object({questionId:z30.uuid(),invocationId:z30.uuid(),askedAt:z30.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z30.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z30.object({question:AgentQuestionSchema,continuationInvocationId:z30.uuid(),deduped:z30.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z31}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=z31.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z31.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z31.enum(["secret_text"]),IntegrationCredentialUsageSchema=z31.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z31.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z31.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z31.object({mode:IntegrationAuthModeSchema,label:z31.string().min(1),description:z31.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z31.object({id:z31.string().min(1),label:z31.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z31.boolean()}),IntegrationToolDefinitionDTOSchema=z31.object({key:z31.string().min(1),name:z31.string().min(1),description:z31.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z31.object({title:z31.string().min(1),description:z31.string().min(1),command:z31.string().min(1).optional()}),IntegrationInfoDTOSchema=z31.object({key:z31.string().min(1),name:z31.string().min(1),summary:z31.string().min(1),type:z31.enum(["native","mcp"]).optional(),url:z31.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z31.array(IntegrationAuthModeDTOSchema),credentials:z31.array(IntegrationCredentialDefinitionDTOSchema),tools:z31.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z31.enum(["available","unavailable"]).optional(),recipes:z31.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z31.object({projectId:z31.uuid(),integrationKey:z31.string().min(1),name:z31.string().min(1),summary:z31.string().min(1),installed:z31.boolean(),enabled:z31.boolean(),setupState:z31.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z31.string().nullable(),connectionId:z31.uuid().nullable().optional(),connectionAlias:z31.string().min(1).nullable().optional(),connectionStatus:z31.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z31.array(z31.string()),installedAt:z31.coerce.date().nullable(),updatedAt:z31.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z31.object({id:z31.uuid(),projectId:z31.uuid(),integrationKey:z31.string().min(1),enabled:z31.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z31.string(),connectionId:z31.uuid().nullable().optional(),connectionAlias:z31.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z31.array(z31.string()),createdAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z31.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z31.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z31.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z31.object({value:z31.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z31.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z31.object({id:z31.uuid(),organizationId:z31.string().min(1),integrationKey:z31.string().min(1),alias:z31.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z31.string().min(1),externalAccountName:z31.string().nullable(),externalBotUserId:z31.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z31.array(z31.string()),connectedAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z31.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z31.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z31.record(McpHeaderNameSchema,z31.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z31.object({alias:z31.string().min(1).max(120).optional(),token:z31.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z31.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=z31.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z31.discriminatedUnion("mode",[z31.object({mode:z31.literal("personal"),alias:z31.string().min(1).max(120),token:z31.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z31.boolean().optional()}),z31.object({mode:z31.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z31.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=z31.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z31.union([z31.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z31.object({type:z31.literal("mcp"),name:z31.string().trim().min(1).max(120),url:z31.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z31.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z31.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=z31.object({integrationKey:z31.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z31.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z31.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z31.literal("oauth"),connectUrl:z31.string().url(),expiresAt:z31.coerce.date()})]),ReusableMcpServerAuthKindSchema=z31.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z31.object({id:z31.uuid(),name:z31.string().min(1),host:z31.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z31.string().min(1),availability:z31.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z31.object({query:z31.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z31.object({serverId:z31.uuid()}),StartProjectIntegrationConnectResponseSchema=z31.object({integrationKey:z31.string().min(1),connectUrl:z31.string().url(),expiresAt:z31.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z31.discriminatedUnion("mode",[z31.object({mode:z31.literal("personal"),integrationKey:z31.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z31.object({mode:z31.literal("oauth"),integrationKey:z31.string().min(1),connectUrl:z31.string().url(),expiresAt:z31.coerce.date()})]),BindProjectChannelRequestSchema=z31.object({ref:z31.string().min(1),connectionAlias:z31.string().min(1).optional(),agentName:z31.string().min(1).max(160).nullable().optional(),force:z31.boolean().optional()}),ListProjectChannelsQuerySchema=z31.object({integrationKey:z31.string().min(1)}),SearchProjectChannelsQuerySchema=z31.object({integrationKey:z31.string().min(1),connectionAlias:z31.string().min(1),query:z31.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z31.object({id:z31.uuid(),projectId:z31.uuid(),integrationKey:z31.string().min(1),connectionId:z31.uuid(),externalWorkspaceId:z31.string().min(1),externalChannelId:z31.string().min(1),externalChannelName:z31.string().nullable(),agentName:z31.string().nullable(),enabled:z31.boolean(),createdAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z31.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z31.object({id:z31.string().min(1),name:z31.string().min(1),visibility:z31.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z31.string().min(1).nullable(),canMove:z31.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z31.object({markdown:z31.boolean().optional(),summary:z31.boolean().optional(),links:z31.boolean().optional(),branding:z31.boolean().optional(),images:z31.boolean().optional(),html:z31.union([z31.literal("cleaned"),z31.literal("raw"),z31.boolean()]).optional(),json:z31.union([z31.boolean(),z31.object({prompt:z31.string().min(1).max(1e4),schema:z31.record(z31.string(),z31.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z31.object({url:z31.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional(),waitForMs:z31.number().int().min(0).max(3e4).optional(),maxAgeMs:z31.number().int().min(0).optional(),minAgeMs:z31.number().int().min(0).optional(),storeInCache:z31.boolean().optional(),proxy:z31.enum(["basic","enhanced","auto"]).optional(),mobile:z31.boolean().optional(),location:z31.object({country:z31.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z31.array(z31.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z31.object({query:z31.string().min(1),maxResults:z31.number().int().positive().max(20).optional(),sources:z31.array(z31.enum(["web","news","images"])).min(1).max(3).optional(),categories:z31.array(z31.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z31.enum(["hour","day","week","month","year"]).optional(),location:z31.string().min(1).max(160).optional(),country:z31.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z31.object({query:z31.string().min(1).max(500),maxResults:z31.number().int().min(1).max(100).optional(),types:z31.array(z31.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z31.array(z31.string().min(1).max(512)).min(1).max(20).optional(),sources:z31.array(z31.string().min(1).max(512)).min(1).max(20).optional(),passages:z31.number().int().min(1).max(5).optional(),skills:z31.literal("only").optional(),language:z31.string().min(1).optional(),topic:z31.string().min(1).optional(),license:z31.string().min(1).optional(),minStars:z31.number().int().min(0).optional(),maxStars:z31.number().int().min(0).optional(),archived:z31.boolean().optional(),fork:z31.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z31.object({query:z31.string().min(1).max(500),maxResults:z31.number().int().min(1).max(500).optional(),authors:z31.array(z31.string().min(1)).min(1).optional(),categories:z31.array(z31.string().min(1)).min(1).optional(),from:z31.iso.date().optional(),to:z31.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z31.object({paperId:z31.string().min(1).max(512),query:z31.string().min(1).max(500).optional(),maxPassages:z31.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z31.object({paperId:z31.string().min(1).max(512),intent:z31.string().min(1).max(500),mode:z31.enum(["similar","citers","references"]).optional(),maxResults:z31.number().int().min(1).max(500).optional(),rerank:z31.boolean().optional(),anchors:z31.array(z31.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z31.object({url:z31.string().url(),search:z31.string().min(1).optional(),limit:z31.number().int().positive().max(200).optional(),includeSubdomains:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z31.object({url:z31.string().url(),limit:z31.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z31.object({text:z31.string().min(1).max(200).optional(),cron:z31.string().min(1).max(120).optional(),timezone:z31.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z31.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional(),waitForMs:z31.number().int().min(0).max(3e4).optional(),maxAgeMs:z31.number().int().min(0).optional(),minAgeMs:z31.number().int().min(0).optional(),storeInCache:z31.boolean().optional(),proxy:z31.enum(["basic","enhanced","auto"]).optional(),mobile:z31.boolean().optional(),location:z31.object({country:z31.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z31.array(z31.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z31.union([z31.object({type:z31.enum(["scrape","crawl"]).default("scrape"),urls:z31.array(z31.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z31.object({type:z31.literal("search"),queries:z31.array(z31.string().min(1).max(256)).min(1).max(12),searchWindow:z31.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z31.number().int().min(1).max(50).optional(),includeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z31.object({name:z31.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z31.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z31.string().min(1).max(2e3).optional(),judgeEnabled:z31.boolean().optional(),retentionDays:z31.number().int().min(1).max(365).optional(),notification:z31.object({email:z31.object({enabled:z31.boolean().default(!0),recipients:z31.array(z31.string().email()).min(1).max(20),includeDiffs:z31.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=z31.object({monitorId:z31.string().uuid(),name:z31.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z31.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z31.string().min(1).max(2e3).optional(),judgeEnabled:z31.boolean().optional(),retentionDays:z31.number().int().min(1).max(365).optional(),status:z31.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z31.object({monitorId:z31.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z31.string().uuid()}),RunProjectIntegrationToolRequestSchema=z31.object({tool:z31.string().min(1),input:z31.record(z31.string(),z31.unknown()),connectionAlias:z31.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z31.object({provider:z31.string().min(1),providerCredits:z31.number().nonnegative().optional(),providerCostUsd:z31.number().nonnegative().optional(),requests:z31.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z31.object({credits:z31.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z31.object({url:z31.string(),provider:z31.literal("firecrawl"),title:z31.string().optional(),statusCode:z31.number().optional(),markdown:z31.string().optional(),summary:z31.string().optional(),links:z31.array(z31.string()).optional(),images:z31.array(z31.string()).optional(),html:z31.string().optional(),json:z31.unknown().optional(),branding:z31.record(z31.string(),z31.unknown()).optional(),warning:z31.string().optional()}),FirecrawlSearchToolOutputSchema=z31.object({query:z31.string(),provider:z31.literal("firecrawl"),warning:z31.string().optional(),results:z31.array(z31.object({title:z31.string(),url:z31.string(),snippet:z31.string().optional(),content:z31.string().optional(),score:z31.number().optional(),publishedAt:z31.string().optional()}))}),FirecrawlResearchPaperSchema=z31.object({paperId:z31.string(),primaryId:z31.string().optional(),ids:z31.record(z31.string(),z31.array(z31.string())).optional(),title:z31.string().optional(),abstract:z31.string().optional(),score:z31.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z31.object({text:z31.string(),score:z31.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),results:z31.array(z31.object({id:z31.string(),type:z31.string().min(1).optional(),url:z31.string(),title:z31.string().optional(),passages:z31.array(z31.object({text:z31.string()}).passthrough())}).passthrough()),coverage:z31.record(z31.string(),z31.string()).optional(),reranked:z31.boolean().optional(),repos:z31.array(z31.record(z31.string(),z31.unknown())).optional(),sources:z31.array(z31.record(z31.string(),z31.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),results:z31.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),paper:z31.record(z31.string(),z31.unknown()),paperId:z31.string().optional(),query:z31.string().optional(),passages:z31.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),results:z31.array(FirecrawlResearchPaperSchema),poolSize:z31.number().int().nonnegative(),truncated:z31.boolean(),note:z31.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z31.object({url:z31.string(),provider:z31.literal("firecrawl"),count:z31.number(),links:z31.array(z31.object({url:z31.string(),title:z31.string().optional(),description:z31.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z31.object({url:z31.string(),provider:z31.literal("firecrawl"),total:z31.number(),pages:z31.array(z31.object({url:z31.string(),title:z31.string().optional(),statusCode:z31.number().optional(),markdown:z31.string().optional(),summary:z31.string().optional(),links:z31.array(z31.string()).optional(),images:z31.array(z31.string()).optional(),html:z31.string().optional(),warning:z31.string().optional()})),warning:z31.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z31.object({cron:z31.string().optional(),text:z31.string().optional(),timezone:z31.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z31.object({id:z31.string().optional(),type:z31.enum(["scrape","crawl","search"]).optional(),urls:z31.array(z31.string()).optional(),queries:z31.array(z31.string()).optional(),searchWindow:z31.string().optional(),maxResults:z31.number().optional(),includeDomains:z31.array(z31.string()).optional(),excludeDomains:z31.array(z31.string()).optional(),scrapeOptions:z31.record(z31.string(),z31.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z31.object({id:z31.string(),name:z31.string(),status:z31.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z31.string().nullable().optional(),lastRunAt:z31.string().nullable().optional(),currentCheckId:z31.string().nullable().optional(),targets:z31.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z31.string().nullable().optional(),judgeEnabled:z31.boolean().optional(),estimatedCreditsPerMonth:z31.number().optional(),createdAt:z31.string().optional(),updatedAt:z31.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z31.object({id:z31.string(),monitorId:z31.string(),scheduledFor:z31.string().nullable().optional(),startedAt:z31.string().nullable().optional(),finishedAt:z31.string().nullable().optional(),estimatedCredits:z31.number().optional(),reservedCredits:z31.number().optional(),actualCredits:z31.number().optional(),billingStatus:z31.string().nullable().optional(),summary:z31.object({totalPages:z31.number().optional(),same:z31.number().optional(),changed:z31.number().optional(),new:z31.number().optional(),removed:z31.number().optional(),error:z31.number().optional()}).passthrough().optional(),error:z31.string().nullable().optional(),createdAt:z31.string().optional(),updatedAt:z31.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitors:z31.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitorId:z31.string(),deleted:z31.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitorId:z31.string(),checks:z31.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitorId:z31.string(),check:FirecrawlMonitorCheckOutputSchema,next:z31.string().optional()}),FirecrawlToolKeySchema=z31.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=z31.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z31.object({projectId:z31.uuid(),integrationKey:z31.string().min(1),tool:z31.string().min(1),connectionAlias:z31.string().min(1).nullable().optional(),output:z31.record(z31.string(),z31.unknown()),executedAt:z31.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z31.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z31.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z31.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z31.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z31.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z31.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z31.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z31.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z31.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z31.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z31.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z31.array(ProjectChannelCandidateDTOSchema))}});import{z as z32}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=z32.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z32.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z32.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z32.object({userId:z32.string().min(1),name:z32.string(),email:z32.string().min(1),subscribed:z32.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z32.object({maxSubscribers:z32.number().int().positive(),subscriberCount:z32.number().int().nonnegative(),effectiveRecipientCount:z32.number().int().nonnegative(),currentUserSubscribed:z32.boolean(),candidates:z32.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z32.object({userIds:z32.array(z32.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z32.object({topic:UserManagedNotificationTopicSchema,enabled:z32.boolean(),source:z32.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z32.object({topics:z32.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z32.object({enabled:z32.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z32.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z32.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z32.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z32.string().nullable(),maskedEmail:z32.string().min(1),applied:z32.boolean(),expiresAt:z32.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z32.object({scheduleId:z32.string().min(1),scheduleName:z32.string(),projectId:z32.string().min(1),projectName:z32.string(),env:z32.string().min(1)}),FollowedSchedulesSchema=z32.object({schedules:z32.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z33}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=z33.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=z33.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z33.uuid(),env:z33.string().min(1),name:z33.string().min(1),cron:z33.string().min(1),command:z33.string().min(1),secretKeys:z33.array(z33.string().min(1)),enabled:z33.boolean(),lastRunAt:z33.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z33.string().nullable(),overPolicyReasons:z33.array(z33.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z33.object({name:z33.string().min(1).max(120),cron:z33.string().min(1).max(120),command:z33.string().min(1).max(500),secretKeys:z33.array(ProjectSecretKeySchema).default([]),enabled:z33.boolean().optional()}),UpdateProjectScheduleRequestSchema=z33.object({name:z33.string().min(1).max(120).optional(),cron:z33.string().min(1).max(120).optional(),command:z33.string().min(1).max(500).optional(),secretKeys:z33.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z33.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z33.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z33.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z33.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z33.object({maxRuns:z33.number().int().positive(),retentionDays:z33.number().int().positive().nullable(),outputRetentionDays:z33.number().int().positive(),maxOutputBytes:z33.number().int().positive()}),SchedulePolicyStateSchema=z33.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z33.object({code:z33.enum(["Free","Premium","Pro"]),source:z33.enum(["cached_subscription","free_fallback"]),activeSchedules:z33.object({used:z33.number().int().nonnegative(),limit:z33.number().int().positive()}),minCadenceMinutes:z33.number().int().positive(),maxRunMs:z33.number().int().positive(),concurrency:z33.object({used:z33.number().int().nonnegative(),limit:z33.number().int().positive()}),compute:z33.object({settledMs:z33.number().int().nonnegative(),reservedMs:z33.number().int().nonnegative(),includedMs:z33.number().int().positive(),remainingMs:z33.number().int().nonnegative(),resetsAt:z33.coerce.date()}),upgrade:z33.object({code:z33.literal("Pro"),activeSchedulesLimit:z33.number().int().positive(),minCadenceMinutes:z33.number().int().positive(),maxRunMs:z33.number().int().positive(),maxConcurrentRuns:z33.number().int().positive(),computeIncludedMs:z33.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z33.array(z33.string())}),ProjectScheduleUsageSchema=z33.object({runCount:z33.number().int().nonnegative(),runsWithOutput:z33.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z33.object({id:z33.uuid(),scheduleId:z33.uuid(),projectId:z33.uuid(),env:z33.string().min(1),scheduleName:z33.string().min(1),command:z33.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z33.object({id:z33.string().min(1),name:z33.string().min(1)}).nullable(),queuedAt:z33.coerce.date(),startedAt:z33.coerce.date().nullable(),finishedAt:z33.coerce.date().nullable(),exitCode:z33.number().int().nullable(),errorCode:z33.string().nullable(),error:z33.string().nullable(),outputBytes:z33.number().int().nonnegative(),outputTruncated:z33.boolean(),outputExpiresAt:z33.coerce.date().nullable(),metadataExpiresAt:z33.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z33.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z33.coerce.date().nullable(),items:z33.array(z33.object({key:z33.string().min(1),updatedAt:z33.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z33.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z33.object({trigger:z33.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z33.object({limit:z33.coerce.number().int().min(1).max(100).default(25),cursor:z33.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z33.object({items:z33.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z33.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z33.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z33.object({items:z33.array(ProjectScheduleRunDTOSchema),nextCursor:z33.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z34}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,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_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z34.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z34.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z34.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z34.discriminatedUnion("kind",[z34.object({kind:z34.literal("user"),userId:z34.string().min(1)}).strict(),z34.object({kind:z34.literal("agent"),agentKey:z34.string().min(1).max(120),agentId:z34.uuid().optional()}).strict(),z34.object({kind:z34.literal("system")}).strict()]),NotificationSummarySchema=z34.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z34.string().trim().min(1).max(120).optional(),brief:ReportBriefSchema.optional()},NotificationRunOutcomeSchema=z34.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z34.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z34.discriminatedUnion("topic",[z34.object({topic:z34.literal("agent_question"),questionId:z34.uuid(),title:z34.string().trim().min(1).max(80),description:z34.string().trim().min(1).max(240)}).strict(),z34.object({topic:z34.literal("agent_run_outcome"),threadId:z34.uuid(),invocationId:z34.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z34.object({topic:z34.literal("agent_retained_review"),threadId:z34.uuid(),invocationId:z34.uuid().optional(),proposalId:z34.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z34.object({topic:z34.literal("agent_conflict"),mergeId:z34.uuid(),threadId:z34.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z34.object({id:z34.uuid(),projectId:z34.uuid(),sourceKey:z34.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z34.literal(1),payload:NotificationPayloadSchema,createdAt:z34.coerce.date()}),NotificationRecipientStateSchema=z34.object({id:z34.uuid(),notificationId:z34.uuid(),projectId:z34.uuid(),userId:z34.string().min(1),readAt:z34.coerce.date().nullable(),archivedAt:z34.coerce.date().nullable(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),NotificationDeliveryStateSchema=z34.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z34.object({id:z34.uuid(),notificationRecipientId:z34.uuid(),projectId:z34.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z34.number().int().nonnegative(),nextAttemptAt:z34.coerce.date().nullable(),lastAttemptAt:z34.coerce.date().nullable(),sentAt:z34.coerce.date().nullable(),failureCode:z34.string().max(80).nullable(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),NotificationPreferenceSchema=z34.object({topic:WorkNotificationTopicSchema,channel:z34.literal("email"),enabled:z34.boolean(),source:z34.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z34.object({topics:z34.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z34.discriminatedUnion("kind",[z34.object({kind:z34.literal("question"),questionId:z34.uuid()}).strict(),z34.object({kind:z34.literal("run_outcome"),threadId:z34.uuid(),invocationId:z34.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z34.object({kind:z34.literal("retained_review"),threadId:z34.uuid(),invocationId:z34.uuid().nullable(),proposalId:z34.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z34.object({kind:z34.literal("merge_conflict"),mergeId:z34.uuid(),threadId:z34.uuid().nullable()}).strict()]),NotificationViewSchema=z34.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z34.object({items:z34.array(NotificationViewSchema),nextCursor:z34.string().nullable(),unreadCount:z34.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z34.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z34.string().min(1).max(120).optional(),sourceKey:z34.string().min(1).max(255).optional(),unread:z34.stringbool().optional(),archived:z34.stringbool().optional(),limit:z34.coerce.number().int().min(1).max(100).optional(),cursor:z34.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=z34.object({recipient:NotificationRecipientStateSchema,unreadCount:z34.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z34.object({read:z34.boolean().optional(),archived:z34.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z35}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=z35.object({surface:SurfaceNameSchema,key:z35.string(),label:z35.string()}),InlineSchema=z35.object({text:z35.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z35.discriminatedUnion("type",[z35.object({type:z35.literal("paragraph"),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("preview"),ref:DiffRefSchema,caption:z35.string().optional()}),z35.object({type:z35.literal("code"),code:z35.string(),lang:z35.string().optional(),caption:z35.string().optional()}),z35.object({type:z35.literal("risk"),level:z35.enum(["warning","error"]),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("list"),items:z35.array(z35.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z35.object({headline:z35.string(),blocks:z35.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z35.object({summary:EnvDiffSummarySchema,fingerprint:z35.string(),generatedAt:z35.coerce.date(),cached:z35.boolean().optional(),credits:z35.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z36}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=z36.object({date:z36.string(),visitors:z36.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z36.object({key:z36.string(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z36.object({path:z36.string(),pageName:z36.string().nullable().optional(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z36.object({preset:z36.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z36.string(),requestedTo:z36.string(),effectiveFrom:z36.string(),effectiveTo:z36.string(),isRetentionLimited:z36.boolean(),groupBy:z36.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z36.object({date:z36.string(),content:z36.string(),updatedAt:z36.string(),updatedByUserId:z36.string()}),ProjectPageviewAnalyticsDTOSchema=z36.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative(),bounceRate:z36.number().min(0).max(100),viewsPerVisit:z36.number().nonnegative(),averageVisitDurationSeconds:z36.number().nonnegative(),visitorsSeries:z36.array(ProjectDailyVisitorsDTOSchema),topPages:z36.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z36.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z37}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=z37.object({id:z37.string(),email:z37.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z37.coerce.date(),createdAt:z37.coerce.date(),inviterUserId:z37.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z37.object({id:z37.string(),token:z37.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z37.object({success:z37.boolean(),projectId:z37.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z38}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=z38.object({id:z38.string(),name:z38.string(),image:z38.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z38.object({count:z38.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z38.object({counts:z38.object({signed_up:z38.int(),activated:z38.int()}),credits:z38.object({total:z38.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z38.email(),emailVerified:z38.boolean(),createdAt:z38.coerce.date(),updatedAt:z38.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z39}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=z39.object({id:z39.string(),principalType:ProjectPrincipalTypeSchema,principalId:z39.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z39.coerce.date(),expiresAt:z39.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=z39.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z39.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z39.record(z39.string(),z39.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z39.object({access:z39.array(ProjectAccessItemDTOSchema),invites:z39.array(ProjectInviteDTOSchema),organization:z39.object({name:z39.string().nullable(),logo:z39.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z39.object({success:z39.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z39.object({success:z39.boolean(),projectId:z39.uuid()}))}});import{z as z40}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=z40.object({publicationStatus:PublicationStatusSchema,appUrl:z40.string().nullable(),lastPublishedAt:z40.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z41}from"zod";var PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,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();PreviewBridgePackageSchema=z41.object({name:z41.string().min(1),version:z41.string().min(1)}),PreviewBridgeCapabilitySchema=z41.object({integrated:z41.boolean(),packages:z41.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z41.object({url:z41.url(),expiresAt:z41.iso.datetime(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z41.object({name:z41.string().min(1),locator:z41.string().min(1).optional(),source:z41.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z41.object({kind:z41.literal("dependency_build_scripts_blocked"),packageManager:z41.enum(["pnpm","yarn","bun"]),packages:z41.array(z41.string()),targets:z41.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z41.string(),approvalKey:z41.string(),command:z41.string().optional(),approval:z41.object({id:z41.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z41.object({code:z41.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z41.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z41.object({approvalId:z41.uuid()}),PreviewInstallPolicyApprovalEventSchema=z41.discriminatedUnion("type",[z41.object({type:z41.literal("progress"),step:z41.enum(["approval","install","restart","readiness"]),message:z41.string()}),z41.object({type:z41.literal("approved")}),z41.object({type:z41.literal("complete")}),z41.object({type:z41.literal("error"),code:z41.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z41.string()})])}});import{z as z42}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:z42.string(),slug:z42.string().nullable(),logo:z42.string().nullable(),metadata:z42.record(z42.string(),z42.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z42.object({id:z42.string(),name:z42.string(),email:z42.email(),image:z42.string().nullable()}),OrganizationMemberDTOSchema=z42.object({id:z42.string(),userId:z42.string(),organizationId:z42.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z42.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z43}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,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=z43.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z43.object({reason:CancellationReasonCodeSchema,details:z43.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z43.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z43.object({offerVersion:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),renewsOn:z43.string()}),PlanMigrationPreviewDTOSchema=z43.object({currency:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),startsAt:z43.string(),renewsAt:z43.string(),nextRenewalAmount:z43.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z43.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z43.object({id:z43.string(),organizationId:z43.string(),legacySubscriptionId:z43.string(),offeredPlanCode:z43.string(),offeredPlanName:z43.string(),offeredPriceAmount:z43.number(),offeredCurrency:z43.string(),offerVersion:z43.string(),state:PlanMigrationStateSchema,checkoutToken:z43.string().nullable(),deadlineAt:z43.string(),transitions:z43.array(z43.object({event:z43.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z43.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z43.object({included:z43.number().optional(),unitPrice:z43.number().optional(),dailyCap:z43.number().nullable().optional()}),EntitlementsDTOSchema=z43.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z43.object({retentionDays:z43.number().int().positive(),canUseExtendedDateRanges:z43.boolean()}).optional(),history:z43.object({retentionDays:z43.number().int().positive()}).optional(),members:z43.object({canInvite:z43.boolean(),maxMembers:z43.number().int().positive().nullable()}).optional(),domains:z43.object({canUseCustomDomains:z43.boolean(),maxDomains:z43.number().int().nonnegative().nullable()}).optional(),media_storage:z43.object({limitBytes:z43.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z43.object({usedBytes:z43.number().int().nonnegative().nullable(),limitBytes:z43.number().int().nonnegative().nullable(),state:z43.enum(["ready","unavailable"]),measuredAt:z43.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),SubscriptionDTOSchema=z43.object({id:z43.string(),external_id:z43.string(),customerId:z43.string(),planId:z43.string(),planCode:z43.union([TemplateCodeSchema,z43.literal("Unknown")]),currentPeriod:z43.object({start:z43.string(),end:z43.string().nullable()}),cancelAt:z43.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z43.string(),nextPaymentAt:z43.string().nullable(),baseAmount:z43.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z43.object({totalCap:z43.number(),dailyCap:z43.number(),usedTotal:z43.number()}),CreditBalanceDTOSchema=z43.object({total:z43.number(),base:z43.number(),dailyBase:z43.number(),purchases:z43.number(),awards:z43.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z43.object({total:z43.number(),nearLimit:z43.boolean(),canChat:z43.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z43.object({dailyFreeAvailable:z43.number(),monthlyAvailable:z43.number(),purchasedAvailable:z43.number(),awardedAvailable:z43.number()}),ProjectDailyCreditAllowanceDTOSchema=z43.object({periodCap:z43.number(),dailyGrant:z43.number(),usedThisPeriod:z43.number(),remainingThisPeriod:z43.number()}),ProjectCreditBalanceDTOSchema=z43.object({projectId:z43.uuid(),organizationId:z43.string(),balance:z43.object({totalAvailable:z43.number(),nearLimit:z43.boolean(),canUseAi:z43.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z43.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z43.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z43.object({planCode:z43.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z43.object({source:z43.enum(["cached_subscription","free_fallback"]),settledMs:z43.number().int().nonnegative(),reservedMs:z43.number().int().nonnegative(),includedMs:z43.number().int().positive(),remainingMs:z43.number().int().nonnegative(),resetsAt:z43.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().nonnegative(),refillAmountUsd:z43.number().nonnegative()}),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().nonnegative().nullable(),refillAmountUsd:z43.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().min(.01).multipleOf(.01),refillAmountUsd:z43.number().min(.01).multipleOf(.01)}).strict(),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z43.object({invoiceId:z43.string(),newBalance:z43.int(),creditCount:z43.int(),amountUsd:z43.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z43.object({url:z43.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 z44}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=z44.object({brand:z44.string(),last4:z44.string(),exp:z44.string(),isDefault:z44.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z45}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=z45.string().superRefine((path53,ctx)=>{let segments=path53.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z45.object({type:z45.literal("renameField"),contentType:z45.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z45.object({enabled:z45.boolean()}).strict(),ContentFieldGroupSchema=z45.object({id:z45.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z45.string().min(1).max(255),default:z45.boolean().optional()}).strict(),ContentTypeDTOSchema=z45.object({id:z45.string(),name:z45.string(),label:z45.string(),isSingleton:z45.boolean(),i18n:ContentTypeI18nSchema,groups:z45.array(ContentFieldGroupSchema).default([]),fields:z45.record(z45.string(),FieldDefinitionSchema),createdAt:z45.string(),updatedAt:z45.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z45.object({contentTypes:z45.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z45.object({id:z45.string(),entryId:z45.string(),documentId:z45.string(),slug:z45.string(),locale:z45.string().optional(),createdAt:z45.string(),updatedAt:z45.string(),__fimo:z45.object({contentType:z45.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({limit:z45.number(),offset:z45.number(),total:z45.number(),hasMore:z45.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z45.object({contentType:z45.string(),count:z45.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z45.object({counts:z45.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z45.object({count:z45.number().int().nonnegative(),sourceLocale:z45.string(),targetLocale:z45.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z45.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z45.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z45.union([z45.string(),z45.number(),z45.boolean(),z45.null()]),entryWhereOperatorSchema=z45.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z45.array(entryWhereScalarSchema).optional(),$nin:z45.array(entryWhereScalarSchema).optional(),$contains:z45.string().optional(),$startsWith:z45.string().optional(),$null:z45.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z45.object({data:z45.record(z45.string(),z45.unknown()),locale:z45.string().min(1).optional(),documentId:z45.uuid().optional()}),entryIdsSchema=z45.array(z45.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z45.object({sql:z45.string().min(1)}),BulkCreateEntriesRequestSchema=z45.object({entries:z45.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z45.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z45.object({updates:z45.array(z45.object({id:z45.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,locale:z45.string().min(1).optional()}),z45.object({where:EntryWhereSchema,locale:z45.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z45.object({data:z45.array(z45.record(z45.string(),z45.unknown())),meta:z45.object({rowCount:z45.number().int().nonnegative(),truncated:z45.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({created:z45.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({updated:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({deleted:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z46}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z46.object({index:z46.number().int().nonnegative(),contentType:z46.string(),field:z46.string(),value:z46.string(),against:z46.enum(["stored","batch"]),ownerDocumentId:z46.uuid().optional(),ownerIndex:z46.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z46.object({code:z46.literal("unique_conflict"),message:z46.string(),conflicts:z46.array(UniqueConflictSchema),truncated:z46.boolean().optional()})}});import{z as z47}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=z47.object({kind:z47.literal("unique_conflict"),contentType:z47.string(),field:z47.string(),value:z47.string(),documentCount:z47.number().int().positive(),documentIds:z47.array(z47.uuid()),documentIdsTruncated:z47.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z47.object({code:z47.literal("schema_transition_rejected"),message:z47.string(),issues:z47.array(SchemaTransitionIssueSchema),truncated:z47.boolean().optional()})}});import{z as z48}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=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z48.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z48.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z48.object({field:CmsFieldNameSchema,direction:z48.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z48.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z48.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z48.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z48.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z48.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z49}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z49.object({id:z49.string(),name:z49.string()}),AssetDTOSchema=z49.object({id:z49.string(),name:z49.string(),type:AssetTypeSchema,originalFileName:z49.string().nullable(),parentId:z49.string().nullable(),mimeType:z49.string().nullable(),fileSize:z49.number().nullable(),url:z49.string().nullable(),storageKey:z49.string().nullable(),createdAt:z49.string(),updatedAt:z49.string(),altText:z49.string().nullable().optional(),caption:z49.string().nullable().optional(),aiCaption:z49.string().nullable().optional(),aiAltText:z49.string().nullable().optional(),aiTags:z49.array(z49.string()).nullable().optional(),aiPrimaryColor:z49.string().nullable().optional(),aiProcessingStatus:z49.string().nullable().optional(),width:z49.number().nullable().optional(),height:z49.number().nullable().optional(),path:z49.array(AssetPathItemSchema).optional(),hasChildren:z49.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z49.lazy(()=>z49.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z49.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z49.object({error:z49.string(),code:z49.literal("media_storage_limit_exceeded"),usedBytes:z49.number().int().nonnegative(),limitBytes:z49.number().int().positive(),incomingBytes:z49.number().int().nonnegative()}),AssetReferenceScopeSchema=z49.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z49.object({assetIds:z49.array(z49.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z49.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z49.object({totalFiles:z49.number().int().nonnegative(),checkedFiles:z49.number().int().nonnegative(),limit:z49.number().int().positive()}),AssetReferenceFindingDTOSchema=z49.object({assetId:z49.uuid(),entryId:z49.string(),documentId:z49.string(),contentType:z49.string(),locale:z49.string().nullable(),slug:z49.string(),fieldPath:z49.string()}),AssetReferenceScopeResultDTOSchema=z49.object({scope:AssetReferenceScopeSchema,label:z49.string(),state:z49.enum(["available","not-published","failed"]),coverage:z49.enum(["complete","partial","failed"]),references:z49.array(AssetReferenceFindingDTOSchema),reason:z49.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z49.discriminatedUnion("type",[z49.object({type:z49.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z49.object({type:z49.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z49.object({type:z49.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z49.object({replacementAssetId:z49.uuid()}),AssetReferenceReplacementResultSchema=z49.object({referencesReplaced:z49.number().int().nonnegative(),entriesChanged:z49.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementErrorCodeSchema=z49.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable"]),AssetReferenceReplacementErrorSchema=z49.object({error:z49.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z49.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z49.object({intent:AssetRemovalIntentSchema,assetIds:z49.array(z49.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z49.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z49.object({id:z49.uuid(),intent:AssetRemovalIntentSchema,assetIds:z49.array(z49.uuid()),replacementAssetId:z49.uuid().nullable(),expiresAt:z49.iso.datetime(),undoable:z49.boolean(),requestedByMe:z49.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalErrorCodeSchema=z49.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z49.object({error:z49.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z50}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z50.object({key:z50.string(),value:z50.string().optional(),defaultValue:z50.string(),locale:z50.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z51}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=z51.object({id:z51.string(),name:z51.string(),type:z51.enum(["file","folder"]),path:z51.string(),children:z51.lazy(()=>z51.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z51.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z51.object({path:z51.string(),exists:z51.boolean(),type:z51.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z52}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=z52.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z52.object({items:z52.array(ProjectMessagePublicDTOSchema),nextCursor:z52.string().nullable()}),ChatLiveTurnDTOSchema=z52.object({invocationId:z52.string(),step:z52.enum(["preparing","working","compacting","merging"]),startedAt:z52.string()}),ChatLiveTurnStateDTOSchema=z52.object({threadId:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z52.object({id:z52.string(),role:z52.enum(["user","assistant"]),parts:z52.array(z52.unknown()),metadata:z52.record(z52.string(),z52.unknown()).nullable(),versionId:z52.string().nullable().optional(),createdAt:z52.date().transform(value=>value.toISOString()),providerMessageId:z52.string().nullable().optional(),invocationId:z52.string().nullable().optional(),invocationStatus:z52.string().nullable().optional(),invocationTerminalReason:z52.string().nullable().optional()}),ChatAttentionDTOSchema=z52.object({type:z52.literal("merge_conflict"),merge:z52.object({mergeId:z52.string().uuid(),projectId:z52.string(),fromEnv:z52.string(),toEnv:z52.string()}),publishAfterMerge:z52.boolean()}),ChatThreadMessagesPageDTOSchema=z52.object({threadId:z52.string().nullable(),title:z52.string().nullable(),messages:z52.array(ChatThreadMessageDTOSchema),nextCursor:z52.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z52.object({kind:z52.literal("replay"),threadId:z52.string(),userMessageId:z52.string()}),ChatQueuedOutcomeDTOSchema=z52.object({kind:z52.literal("queued"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string()}),ChatBusyOutcomeDTOSchema=z52.object({kind:z52.literal("busy"),threadId:z52.string(),userMessageId:z52.string(),blockingRootId:z52.string().optional()}),ChatRefusedOutcomeDTOSchema=z52.object({kind:z52.literal("refused"),threadId:z52.string(),userMessageId:z52.string(),refusedInvocationId:z52.string(),terminalReason:z52.string()}),ChatNonStreamingOutcomeDTOSchema=z52.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z52.object({success:z52.boolean(),deletedCount:z52.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z52.object({code:z52.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z52.string()})}});import{z as z53}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=z53.object({url:z53.string().url(),key:z53.string(),size:z53.number(),contentType:z53.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z54}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=z54.object({canAccess:z54.boolean(),permissions:z54.record(z54.string(),z54.boolean()),role:z54.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z55}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:z55.string().trim().default(""),sort:z55.enum(["recent","name","relevance"]).default("recent"),category:z55.string().optional()})}});import{z as z56}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=z56.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z56.enum(["fimo","external"]),PaymentStatusSchema=z56.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z56.object({id:z56.string().uuid(),domain:z56.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z56.boolean(),price:z56.number().int().nullable(),renewalPrice:z56.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z56.string().nullable(),failureReason:z56.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z56.object({domain:z56.string(),available:z56.boolean(),premium:z56.boolean(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),purchaseType:z56.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z56.object({domain:z56.string(),price:z56.number().nullable(),renewalPrice:z56.number().nullable(),premium:z56.boolean(),allowedYears:z56.array(z56.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z56.object({firstName:z56.string().max(100),lastName:z56.string().max(100),companyName:z56.string().max(100).optional(),address1:z56.string().max(255),address2:z56.string().max(255).optional(),city:z56.string().max(100),state:z56.string().max(100),zip:z56.string().max(20),country:z56.string().max(2),phone:z56.string().max(30),email:z56.union([z56.string().email().max(255),z56.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z56.object({firstName:z56.string().min(1).max(100),lastName:z56.string().min(1).max(100),companyName:z56.string().max(100).optional(),address1:z56.string().min(1).max(255),address2:z56.string().max(255).optional(),city:z56.string().min(1).max(100),state:z56.string().min(1).max(100),zip:z56.string().min(1).max(20),country:z56.string().min(1).max(2),phone:z56.string().min(1).max(30),email:z56.string().email().max(255)}),SearchDomainsRequestSchema=z56.object({keyword:z56.string().min(1).max(100),tldFilter:z56.array(z56.string()).optional()}),CheckAvailabilityRequestSchema=z56.object({domains:z56.array(z56.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=z56.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z56.object({domain:DomainNameSchema,years:z56.number().int().min(1).max(10).optional().default(3),autoRenew:z56.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z56.object({autoRenew:z56.boolean().optional()}),RenewDomainRequestSchema=z56.object({years:z56.number().int().min(1).max(10).optional().default(1),autoRenew:z56.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z56.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z56.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z56.object({verified:z56.boolean(),email:z56.string().nullable(),verifyBy:z56.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z57}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=z57.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=z57.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=z57.object({txtName:z57.string().nullable().optional(),txtValue:z57.string().nullable().optional(),httpUrl:z57.string().nullable().optional(),httpBody:z57.string().nullable().optional(),cname:z57.string().nullable().optional(),cnameTarget:z57.string().nullable().optional()}),SSLValidationErrorSchema=z57.object({message:z57.string()}),OwnershipVerificationSchema=z57.object({type:z57.string(),name:z57.string(),value:z57.string()}),ProjectDomainSSLDTOSchema=z57.object({status:z57.string(),method:z57.string().nullable(),type:z57.string().nullable(),validationRecords:z57.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z57.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z57.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z57.enum(["subdomain","apex"]),RedirectConfigSchema=z57.object({type:z57.literal("apex_to_www"),linkedDomainId:z57.string()}).nullable().optional(),ProjectDomainDTOSchema=z57.object({id:z57.string(),hostname:z57.string(),status:z57.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z57.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z57.string(),scdCnameTarget:z57.string().optional(),apexTargets:z57.array(z57.string()),dnsAutoConfigured:z57.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z57.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z57.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z57.object({hostname:z57.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:z57.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z57.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z57.object({success:z57.boolean(),hostname:z57.string()}))}});import{z as z58}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=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z58.object({slug:z58.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z58.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z58.object({subdomain:z58.string(),subdomainUpdatedAt:z58.coerce.date()})),SubdomainSuggestionsQuerySchema=z58.object({base:z58.string().max(100).optional(),max:z58.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z58.object({suggestions:z58.array(z58.string())}))}});import{z as z59}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=z59.object({translated:z59.number().int().nonnegative(),total:z59.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z59.object({locale:z59.string(),isDefault:z59.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z59.object({defaultLocale:z59.string(),locales:z59.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z59.object({locale:z59.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z59.object({locale:z59.string().min(1).max(40)}),ProjectLocaleMutationSchema=z59.object({locale:z59.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z59.object({locale:z59.string(),entriesDeleted:z59.number().int().nonnegative(),labelsDeleted:z59.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z60}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=z60.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z60.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=z60.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z60.number(),credits:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),confidence:z60.enum(["exact","estimated","metered"]),basis:z60.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z61}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=z61.object({options:z61.record(z61.string(),z61.unknown()),name:z61.string().optional(),parentId:z61.string().nullable().optional(),altText:z61.string().optional(),caption:z61.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z61.string().min(1).optional(),model:z61.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=z61.object({jobId:z61.string(),status:z61.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z61.string().nullable().optional(),credits:z61.number().optional(),costUsd:z61.number().optional(),billingMode:z61.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z61.object({error:z61.string(),code:z61.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:z61.array(GenerationTaskIdSchema).optional(),availableModels:z61.array(z61.string()).optional(),issues:z61.array(z61.unknown()).optional()})}});import{z as z62}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=z62.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z62.object({name:z62.string(),key:z62.string(),description:z62.string(),type:FlagTypeSchema,required:z62.boolean(),defaultValue:z62.unknown().optional(),enumValues:z62.array(z62.string()).optional(),isArray:z62.boolean()}),AssetModelPriceSchema=z62.object({unitPrice:z62.number(),unit:z62.string(),confidence:z62.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z62.object({id:z62.string(),shortName:z62.string(),provider:z62.string(),source:z62.string(),modality:z62.enum(["image","video","audio"]),tags:z62.array(z62.string()),displayName:z62.string(),description:z62.string(),flags:z62.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z62.object({model:z62.string(),costUsd:z62.number(),credits:z62.number(),billingMode:z62.enum(["fimo-credits","provider-account"]),confidence:z62.enum(["exact","estimated","metered"]),basis:z62.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z63}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=z63.object({tourId:z63.string(),version:z63.string(),status:z63.string(),completedAt:z63.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z63.array(UserTourDTOSchema))}});import{z as z64}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=z64.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z64.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z64.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z64.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z64.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z64.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z64.enum(["user","agent","system"]),SupportReportTagSchema=z64.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z64.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z64.object({organization:z64.object({id:z64.string().trim().min(1).max(255),name:z64.string().trim().max(240).optional()}),project:z64.object({id:z64.uuid(),name:z64.string().trim().max(240).optional(),createdAt:z64.coerce.date().optional()}).optional(),environment:z64.string().trim().max(255).optional(),clientVersion:z64.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z64.object({message:z64.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z64.string().trim().max(200).optional(),limit:z64.coerce.number().int().min(1).max(100).default(50),offset:z64.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z64.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z64.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z64.uuid().nullable().optional(),note:z64.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=z64.object({message:z64.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z64.object({kind:SupportReportLinkKindSchema,label:z64.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z64.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z64.object({kind:SupportReportActorKindSchema,id:z64.string().nullable(),name:z64.string().nullable()}),SupportReportLinkDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportLinkKindSchema,label:z64.string(),url:SupportReportHttpUrlSchema,externalId:z64.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z64.object({id:z64.uuid(),kind:SupportReportEventKindSchema,body:z64.string().nullable(),metadata:z64.record(z64.string(),z64.unknown()),actor:SupportReportActorDTOSchema,createdAt:z64.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z64.object({id:z64.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z64.array(z64.string()),source:SupportReportSourceSchema,message:z64.string(),reporter:z64.object({id:z64.string().nullable(),name:z64.string().nullable(),email:z64.string().nullable()}),organization:z64.object({id:z64.string().nullable(),name:z64.string()}),project:z64.object({id:z64.uuid().nullable(),name:z64.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z64.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z64.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z64.string().nullable(),deliveredAt:z64.coerce.date().nullable()}).nullable(),duplicateOfReportId:z64.uuid().nullable(),resolvedAt:z64.coerce.date().nullable(),createdAt:z64.coerce.date(),updatedAt:z64.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z64.string().nullable(),clientVersion:z64.string().nullable(),links:z64.array(SupportReportLinkDTOSchema),events:z64.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z64.object({reports:z64.array(SupportReportSummaryDTOSchema),total:z64.number().int().nonnegative(),statusCounts:z64.object({new:z64.number().int().nonnegative(),in_progress:z64.number().int().nonnegative(),waiting:z64.number().int().nonnegative(),resolved:z64.number().int().nonnegative(),duplicate:z64.number().int().nonnegative(),irrelevant:z64.number().int().nonnegative(),ignored:z64.number().int().nonnegative()}),limit:z64.number().int().positive(),offset:z64.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z64.object({id:z64.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z64.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z65}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=z65.iso.datetime({offset:!0}).pipe(z65.coerce.date()),OpsRecentChatInputSchema=z65.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z65.string().trim().min(1).max(255).optional(),limit:z65.coerce.number().int().min(1).max(200).default(100),cursor:z65.string().trim().min(1).max(2e3).optional(),slim:z65.boolean().default(!0),reason:z65.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=z65.object({id:z65.string(),threadId:z65.string(),providerMessageId:z65.string().nullable(),invocationId:z65.string().nullable(),env:z65.string().nullable(),role:z65.string(),parts:z65.array(z65.record(z65.string(),z65.unknown())),metadata:z65.object({status:z65.string().optional(),traceUrl:z65.string().optional(),externalFileChanges:z65.array(z65.unknown()).optional()}),stats:z65.object({toolCount:z65.number().int().nonnegative(),failedToolCount:z65.number().int().nonnegative()}),createdAt:z65.iso.datetime({offset:!0}),project:z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),organizationId:z65.string().nullable()})}),OpsRecentChatResponseSchema=z65.object({target:z65.object({backendProfile:OpsBackendProfileSchema,projectEnv:z65.string().nullable()}),window:z65.object({from:z65.iso.datetime({offset:!0}),to:z65.iso.datetime({offset:!0})}),messages:z65.object({items:z65.array(OpsRecentChatMessageSchema),nextCursor:z65.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z66}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=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z66.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z66.object({backendProfile:OpsBackendProfileSchema,provider:z66.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z66.literal(!1),reason:z66.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z67}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=z67.object({packageManager:z67.string().trim().min(1).max(200).nullable(),trackedLockfiles:z67.array(z67.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z67.string().trim().min(1)}),OpsProjectPackageManagerSchema=z67.object({target:z67.object({backendProfile:OpsBackendProfileSchema,projectId:z67.uuid(),projectEnv:z67.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z68}from"zod";function createAgentRunWebhookEventDataSchema(status){return z68.object({run:z68.object({id:z68.string(),agentName:z68.string(),trigger:z68.string(),status:z68.literal(status),startedAt:z68.string().nullable(),finishedAt:z68.string().nullable(),reason:z68.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=z68.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z68.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z68.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z68.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z68.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z68.union([z68.literal(0),z68.literal(5),z68.literal(30),z68.literal(60)]),EntryChangedWebhookEventDataSchema=z68.object({reason:WebhookEntryChangeReasonSchema,operationId:z68.string().optional(),batch:z68.object({index:z68.number().int().positive(),total:z68.number().int().positive()}).optional(),changes:z68.array(z68.object({action:WebhookEntryChangeActionSchema,contentType:z68.string(),id:z68.string(),documentId:z68.string(),locale:z68.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z68.object({form:z68.object({id:z68.string(),label:z68.string()}),submission:z68.object({id:z68.string(),data:z68.record(z68.string(),z68.unknown()),submittedAt:z68.string()})}),PublishStartedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("publishing"),startedAt:z68.string()})}),PublishSucceededWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("published"),url:z68.string(),publishedAt:z68.string(),firstPublish:z68.boolean()})}),PublishFailedWebhookEventDataSchema=z68.object({publication:z68.object({status:z68.literal("failed"),reason:z68.string()})}),PublishUnpublishedWebhookEventDataSchema=z68.object({publication:z68.object({previousUrl:z68.string(),unpublishedAt:z68.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),classification:z68.string(),summary:z68.string(),reasons:z68.array(z68.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z68.object({review:z68.object({id:z68.string(),runId:z68.string(),agentName:z68.string(),resolution:z68.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z68.object({report:z68.object({weekStart:z68.string(),weekEnd:z68.string(),pageviews:z68.number(),visitors:z68.number(),previousPageviews:z68.number(),previousVisitors:z68.number()})}),MediaAssetWebhookEventDataSchema=z68.object({id:z68.string().nullable(),name:z68.string().nullable(),type:z68.string(),mimeType:z68.string().nullable(),fileSize:z68.number().nullable()}),MediaUploadedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["updated","moved","analysis"]),analysis:z68.object({category:z68.string(),status:z68.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.literal("generated"),generation:z68.object({model:z68.string(),mode:z68.string()})}),MediaProcessingFailedWebhookEventDataSchema=z68.object({asset:MediaAssetWebhookEventDataSchema,operation:z68.enum(["analysis","generation"]),failure:z68.object({code:z68.string()})}),DomainCreatedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z68.object({domain:z68.object({id:z68.string(),hostname:z68.string()})}),LabelChangedWebhookEventDataSchema=z68.object({changes:z68.array(z68.object({action:z68.enum(["created","updated","deleted"]),key:z68.string(),locale:z68.string(),value:z68.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),isDefault:z68.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),previousCode:z68.string()})}),LocaleDeletedWebhookEventDataSchema=z68.object({locale:z68.object({code:z68.string(),entriesDeleted:z68.number().int().nonnegative(),labelsDeleted:z68.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z68.object({merge:z68.object({id:z68.string(),from:BranchSchema,to:BranchSchema,applied:z68.array(z68.object({surface:SurfaceNameSchema,count:z68.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z68.object({environment:z68.object({name:BranchSchema}),version:z68.object({versionId:z68.uuid(),name:z68.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=z68.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z68.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z68.discriminatedUnion("source",[z68.object({source:z68.literal("literal"),value:z68.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z68.object({source:z68.literal("secret"),key:z68.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z68.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z68.object({name:z68.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z68.object({name:z68.string(),source:z68.enum(["literal","secret"]),secretKey:z68.string().nullable(),secretPrefix:z68.string().nullable(),configured:z68.literal(!0)}),WebhookFilterSchema=z68.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z68.string().min(1).max(255).optional(),agentName:z68.string().min(1).max(120).optional(),mediaType:z68.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z68.string().min(1).max(255).optional(),locale:z68.string().min(1).max(120).optional()}),JsonValueSchema=z68.lazy(()=>z68.union([z68.string(),z68.number(),z68.boolean(),z68.null(),z68.array(JsonValueSchema),z68.record(z68.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z68.url(),enabled:z68.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z68.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z68.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z68.object({name:z68.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z68.url().optional(),enabled:z68.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z68.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z68.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z68.object({eventType:WebhookEventTypeSchema.optional(),data:z68.record(z68.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z68.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z68.uuid(),name:z68.string(),eventType:WebhookEventTypeSchema,enabled:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z68.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z68.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z68.coerce.date().nullable(),deliveryStats24h:z68.object({succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z68.uuid(),projectId:z68.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z68.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z68.number().int().positive(),test:z68.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z68.number().int().nonnegative(),responseStatus:z68.number().int().nullable(),lastErrorCode:z68.string().nullable(),lastErrorMessage:z68.string().nullable(),payloadAvailable:z68.boolean(),destination:z68.object({host:z68.string(),maskedUrl:z68.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z68.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z68.string().nullable(),qstashMessageId:z68.string().nullable(),deliveredAt:z68.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z68.object({items:z68.array(WebhookDeliveryDTOSchema),pagination:z68.object({page:z68.number().int().positive(),limit:z68.number().int().positive(),total:z68.number().int().nonnegative(),totalPages:z68.number().int().positive(),hasMore:z68.boolean()}),stats:z68.object({total:z68.number().int().nonnegative(),succeeded:z68.number().int().nonnegative(),failed:z68.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z68.object({id:z68.uuid(),deliveryId:z68.uuid(),attempt:z68.number().int().positive(),status:z68.enum(["delivering","succeeded","failed"]),responseStatus:z68.number().int().nullable(),durationMs:z68.number().int().nonnegative(),responseExcerpt:z68.string().nullable(),errorCode:z68.string().nullable(),errorMessage:z68.string().nullable(),createdAt:z68.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z68.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z68.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z69}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=z69.object({key:z69.literal("fimo-2"),enabled:z69.boolean(),dismissed:z69.boolean().default(!1),interacted:z69.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z70}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=z70.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z70.object({total:z70.number(),base:z70.number(),purchases:z70.number(),awards:z70.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z70.object({id:z70.string(),name:z70.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z70.object({type:z70.string(),brand:z70.string().nullable(),last4:z70.string().nullable(),expirationDate:z70.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z70.object({currency:z70.string(),nextPaymentAmount:z70.number().nullable(),nextPaymentAt:z70.string().nullable(),billingInterval:z70.string().nullable(),totalAmount:z70.number().nullable(),discountAmount:z70.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z70.object({id:z70.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z70.string().nullable(),currentPeriodEndsAt:z70.string().nullable(),renewsAt:z70.string().nullable(),cancelAt:z70.string().nullable(),renewAutomatically:z70.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z70.object({type:z70.enum(["low_balance","critical_balance","approaching_limit"]),message:z70.string(),estimatedPromptsRemaining:z70.number().nullable(),avgCostPerPrompt:z70.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z70.object({monthlyCredits:z70.number().nullable(),usedThisPeriod:z70.number(),remainingThisPeriod:z70.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z70.object({organizationId:z70.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z70.string().nullable(),tenureDays:z70.number().int().nonnegative(),capturedAt:z70.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z70.object({hasSubscription:z70.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z70.number().nullable(),alerts:z70.array(CreditAlertDTOSchema),portalUrl:z70.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z70.object({creditCount:z70.number().int().positive(),expiresAt:z70.string().datetime().nullable().optional(),message:z70.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("free"),amountCents:z70.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z70.literal("purchase"),amountCents:z70.number().int().positive()}),CreditTopupRequestDTOSchema=z70.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z70.object({success:z70.boolean(),transactionId:z70.string().nullable(),newBalance:z70.number(),creditCount:z70.number(),type:z70.enum(["free","purchase"]),invoiceId:z70.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z71}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=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),periodStart:z71.string().nullable(),periodEnd:z71.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().email().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z71.array(UsageByUserForProjectDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z71.object({summary:UsageSummaryDTOSchema,byProject:z71.array(UsageByProjectDTOSchema),byUser:z71.array(UsageByUserDTOSchema),timeline:z71.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z72}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=z72.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z72.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z72.object({startDate:z72.string().optional(),endDate:z72.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z72.coerce.number().int().positive().default(1),limit:z72.coerce.number().int().positive().max(100).default(20),sortBy:z72.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z72.string().optional(),activeOnly:z72.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z72.object({totalCredits:z72.number(),totalCostUsd:z72.number(),totalMessages:z72.number(),avgCostPerMessage:z72.number(),avgCreditsPerMessage:z72.number(),periodStart:z72.string(),periodEnd:z72.string(),creditsChange:z72.number().nullable(),costChange:z72.number().nullable(),messagesChange:z72.number().nullable(),unattributedCredits:z72.number(),unattributedCostUsd:z72.number(),unattributedMessages:z72.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z72.object({date:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z72.object({organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number(),projectCount:z72.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z72.object({userId:z72.string(),userName:z72.string().nullable(),userEmail:z72.string().nullable(),userImage:z72.string().nullable(),organizationId:z72.string().nullable(),organizationName:z72.string().nullable(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),projectCount:z72.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z72.object({projectId:z72.string(),projectName:z72.string(),projectDisplayName:z72.string().nullable(),organizationId:z72.string(),organizationName:z72.string(),credits:z72.number(),costUsd:z72.number(),messages:z72.number(),percentage:z72.number(),userCount:z72.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z72.object({id:z72.string(),name:z72.string(),value:z72.number(),percentage:z72.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z72.object({day:z72.number(),hour:z72.number(),value:z72.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z72.object({summary:UsageOverviewSummaryDTOSchema,timeline:z72.array(UsageTimelinePointDTOSchema),topOrganizations:z72.array(OrganizationUsageRowDTOSchema),topUsers:z72.array(UserUsageRowDTOSchema),topProjects:z72.array(ProjectUsageRowDTOSchema),creditDistribution:z72.array(UsageDistributionItemDTOSchema),userDistribution:z72.array(UsageDistributionItemDTOSchema),heatmap:z72.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z72.object({page:z72.number(),limit:z72.number(),totalItems:z72.number(),totalPages:z72.number(),hasMore:z72.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z72.object({organizations:z72.array(OrganizationUsageRowDTOSchema),top:z72.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z72.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z72.object({users:z72.array(ExtendedUserUsageRowDTOSchema),top:z72.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z72.object({projects:z72.array(ExtendedProjectUsageRowDTOSchema),top:z72.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z72.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z72.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z72.object({credits:z72.number(),costUsd:z72.number(),messages:z72.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),createdAt:z72.string(),memberCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z72.object({id:z72.string(),name:z72.string().nullable(),email:z72.string(),image:z72.string().nullable(),createdAt:z72.string(),organizationCount:z72.number(),projectCount:z72.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z72.object({id:z72.string(),name:z72.string(),displayName:z72.string().nullable(),createdAt:z72.string(),organizationId:z72.string(),organizationName:z72.string(),ownerId:z72.string(),ownerName:z72.string().nullable(),ownerEmail:z72.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z72.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z73}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=z73.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z73.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z73.object({command:z73.string().min(1).max(1e4),cwd:z73.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z73.record(z73.string(),z73.string()).optional(),name:z73.string().optional(),waitForCompletion:z73.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z73.object({identifier:z73.string(),status:SandboxProcessStatusSchema,command:z73.string().optional(),startedAt:z73.string().optional(),exitCode:z73.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z73.object({processes:z73.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z73.object({processId:z73.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z73.object({success:z73.boolean(),message:z73.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z74}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_agent_report();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_control_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_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&¶ms.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:path53,message}=issue;return`${Array.isArray(path53)&&path53.length>0?`${path53.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,branch,base)===normalized?base:void 0}catch{return}}function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_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,path53,status,detail,code2,body){super(`API ${method} ${path53} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path53,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__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_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}branch;withBranch(branch){let next2=new _FimoApiClient(this.cfg);return next2.branch=branch,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(path53,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.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...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",path53,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path53,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.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch),fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers})}async rawRequest(path53,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...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"} ${path53} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: tenant-scoped call requires a Branch. Use `client.withBranch(branch)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}projectBranchManagementPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: Branch-scoped management call requires a Branch. Use `client.withBranch(branch)` before calling Branch CRUD methods.");return`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,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&¶ms.set("limit",String(query.limit)),query.before&¶ms.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&¶ms.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&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectBranchManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(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&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,options={}){let query=`?page=${options.page??1}&limit=${options.limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data}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 listBranches(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentBranches&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/branches${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listBranches(projectId,{includeAgentBranches:!0}),current=branches.find(candidate=>branchNameOf(candidate)===branch),visited=new Set;for(;current&&!visited.has(branchNameOf(current));){if(visited.add(branchNameOf(current)),current.resolvedEnvironment)return current.resolvedEnvironment.id;let parent2=parentBranchOf(current);current=parent2?branches.find(candidate=>branchNameOf(candidate)===parent2):void 0}return PREVIEW_ENVIRONMENT_KEY}async getBranch(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`)).data}async createBranch(projectId,input){return(await this.request(`/api/management/projects/${projectId}/branches`,{method:"POST",body:JSON.stringify(input)})).data}async syncBranch(projectId,branch,input={}){let body=await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/sync`,{method:"POST",body:JSON.stringify(input)});return{branch:body.data.branch??body.data.env,conflicts:body.data.conflicts}}async deleteBranch(projectId,branch){await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`,{method:"DELETE"})}async getBranchDiff(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff${qs?`?${qs}`:""}`)).data}async getBranchStatus(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,branch,path53,opts={}){let qs=lazyFetchQs(opts.against,{path:path53});return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,branch,fromBranch,filePath){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,branch,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getSchemaTypeDiff(projectId,branch,typeName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getAssetDiff(projectId,branch,assetId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getTranslationRowDiff(projectId,branch,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getFormSchemaDiff(projectId,branch,formName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async mergeBranch(projectId,branch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,branch,mergeId){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflicts`)).data}async putResolveDraft(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/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,branch,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.branch&¶ms.set("env",opts.branch),opts.status&¶ms.set("status",opts.status),opts.page!==void 0&¶ms.set("page",String(opts.page)),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)}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,branch){let remote=(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,branch);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectBranchManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox`)).data}async getSandboxLogs(projectId,branch,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&¶ms.set("noRestart","true"),options.wait!==void 0&¶ms.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/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(`
|
|
60
|
+
`)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}function escapeCell(value){return value.replace(/\|/g,"\\|").replace(/\n/g," ")}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z15.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z15.object({type:z15.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index2)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index2,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z15.object({type:z15.literal("list"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema.optional(),label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index2)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z15.object({type:z15.literal("media"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z15.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z15.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(normalizeReportDocument,"normalizeReportDocument");__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(reportBlockMarkdown,"reportBlockMarkdown");__name(flattenReportDocument,"flattenReportDocument");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue");__name(escapeCell,"escapeCell")}});import{z as z16}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=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.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:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.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(path53){return[...path53.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path53){return pageRouteParamNames(path53).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 z17}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=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),previewEnabled:z17.boolean().default(!0),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),snapshotUrl:z17.string().startsWith("/").optional(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}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=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}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=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}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=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}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=z22.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z22.object({type:z22.literal("manual")}),ScheduleTriggerSchema=z22.object({type:z22.literal("schedule"),cron:z22.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:z22.string().optional()}),WebhookTriggerSchema=z22.object({type:z22.literal("webhook"),path:z22.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z22.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z23}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=z23.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z23.object({token:z23.string().min(1),risk:CapabilityRiskTierSchema,description:z23.string()}),AgentSubAgentSummarySchema=z23.object({name:z23.string().min(1),grant:z23.enum(["inherit","explicit"]),effectiveCaps:z23.array(z23.string().min(1))}),AgentInstallSummaryDTOSchema=z23.object({agentName:z23.string().min(1),env:z23.string().min(1),declaredCapabilities:z23.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z23.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z23.array(CapabilitySummaryEntrySchema),criticalCapabilities:z23.array(CapabilitySummaryEntrySchema),subAgents:z23.array(AgentSubAgentSummarySchema),declaresDelegate:z23.boolean(),cycle:z23.array(z23.string()).nullable(),missingSubAgents:z23.array(z23.string()),warnings:z23.array(z23.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z24}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=z24.object({kind:TriggerKindSchema,summary:z24.string()}),AgentListItemTriggerStateSchema=z24.object({triggerIndex:z24.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z24.boolean(),wired:z24.boolean(),syncError:z24.string().nullable()}),AgentListItemDTOSchema=z24.object({name:z24.string().min(1),description:z24.string().nullable(),goalFirstLine:z24.string().nullable(),declaredCapabilities:z24.array(CapabilitySummaryEntrySchema),triggers:z24.array(AgentListItemTriggerSchema),triggerStates:z24.array(AgentListItemTriggerStateSchema),paused:z24.boolean(),nextRunAt:z24.coerce.date().nullable()}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z24.array(AgentListItemDTOSchema))}});import{z as z25}from"zod";var AgentControlResultSchema,AgentControlResultDTO,AgentControlResultResponseSchema,init_agent_control_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-control.dto.js"(){"use strict";init_create_dto();init_response();AgentControlResultSchema=z25.object({paused:z25.boolean(),cancelledRuns:z25.number().int().nonnegative(),stopIncomplete:z25.boolean()}),AgentControlResultDTO=createDTO(AgentControlResultSchema),AgentControlResultResponseSchema=createResponseSchema(AgentControlResultSchema)}});import{z as z26}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=z26.object({args:z26.unknown().optional(),requestId:z26.string().min(1).max(128).optional()}),DispatchSkippedSchema=z26.object({skipped:z26.enum(["no-manual-trigger","trigger-not-wired","agent-paused","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z26.object({sessionId:z26.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z26.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z27}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=z27.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z27.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z27.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z27.object({verb:SurfaceDeltaVerbSchema,key:z27.string(),detail:z27.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z27.record(z27.string(),z27.unknown()).optional()}),PerSurfaceDeltaSchema=z27.object({surface:SurfaceNameSchema,status:z27.enum(["ok","timed_out","failed","unchanged"]),durationMs:z27.number().int().nonnegative().optional(),changedCount:z27.number().int().nonnegative(),conflictCount:z27.number().int().nonnegative(),items:z27.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z27.boolean().optional(),error:z27.string().optional()}),CrossSurfaceFindingSchema=z27.object({id:z27.string(),kind:z27.string(),description:z27.string(),severity:z27.enum(["warning","error"]),source:z27.object({surface:SurfaceNameSchema,key:z27.string()}),target:z27.object({surface:SurfaceNameSchema,key:z27.string()}),actions:z27.array(z27.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z27.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z27.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),agents:z27.array(z27.object({id:z27.string(),name:z27.string(),status:z27.enum(["active","paused","failed"]),lastRunAt:z27.coerce.date().nullable()})).optional(),crossSurface:z27.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z27.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),crossSurface:z27.array(CrossSurfaceFindingSchema).optional(),fingerprint:z27.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z27.object({path:z27.string(),state:z27.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z27.string(),additions:z27.number().int().nonnegative(),deletions:z27.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z27.object({oid:z27.string().optional(),content:z27.string().optional(),truncated:z27.boolean(),binary:z27.boolean()}),CodeConflictDetailSchema=z27.object({path:z27.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z27.string(),targetTipSha:z27.string(),mergeBaseSha:z27.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z27.object({id:z27.string(),slug:z27.string(),contentType:z27.string(),data:z27.record(z27.string(),z27.unknown()),updatedAt:z27.coerce.date()}),ContentRowDiffSchema=z27.object({collection:z27.string(),rowId:z27.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z27.object({name:z27.string(),label:z27.string(),isSingleton:z27.boolean(),fields:z27.record(z27.string(),z27.unknown())}),SchemaTypeDiffSchema=z27.object({typeName:z27.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z27.object({id:z27.string(),name:z27.string(),type:z27.enum(["file","folder"]),mimeType:z27.string().nullable(),storageKey:z27.string().nullable(),url:z27.string().nullable(),fileSize:z27.number().nullable(),width:z27.number().nullable(),height:z27.number().nullable(),altText:z27.string().nullable(),caption:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AssetDiffSchema=z27.object({assetId:z27.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z27.object({locale:z27.string(),key:z27.string(),parent:z27.string().nullable(),child:z27.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z27.object({formName:z27.string(),label:z27.string().nullable(),schemaFingerprint:z27.string(),fields:z27.record(z27.string(),z27.unknown()),settings:z27.record(z27.string(),z27.unknown()).optional()}),FormSchemaDiffSchema=z27.object({formName:z27.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=z27.enum(CONFLICT_KINDS),ConflictSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),kind:ConflictKindSchema.optional(),description:z27.string(),parentValue:z27.unknown().optional(),childValue:z27.unknown().optional(),conflictingFields:z27.array(z27.string()).optional(),code:z27.object({path:z27.string(),unresolvable:z27.boolean().optional(),reason:z27.string().optional()}).optional()}),FieldPickSchema=z27.object({field:z27.string(),choice:z27.enum(["parent","child","pick","ai-pick"]),pickedValue:z27.unknown().optional(),aiSessionId:z27.string().optional()}),ConflictResolutionSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),choice:z27.enum(["parent","child","pick"]),pickedValue:z27.unknown().optional(),fieldPicks:z27.array(FieldPickSchema).optional()}),MergeResultSchema=z27.object({ok:z27.boolean(),mergeId:z27.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z27.array(z27.object({surface:SurfaceNameSchema,count:z27.number().int().nonnegative()})),conflicts:z27.array(ConflictSchema).optional(),summary:z27.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z27.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z27.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z27.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z27.boolean().optional()}),ResolvedStrategySchema=z27.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z27.boolean()}),MergeRequestSchema=z27.object({from:BranchSchema,allowDirectMerge:z27.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z27.object({mergeId:z27.string().uuid(),streamUrl:z27.string(),strategy:ResolvedStrategySchema,acceptedAt:z27.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z27.object({mergeId:z27.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z27.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z27.array(ConflictSchema),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedBy:z27.string().nullable(),lastEditedAt:z27.coerce.date().nullable(),initiator:z27.object({userId:z27.string().nullable(),role:z27.string().nullable(),agentName:z27.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z27.object({resolutions:z27.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z27.object({mergeId:z27.string().uuid(),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedAt:z27.coerce.date(),lastEditedBy:z27.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z27.object({mergeId:z27.string().uuid(),resolutions:z27.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z27.object({mergeId:z27.string().uuid()}),PublishReleaseRequestSchema=z27.object({version:z27.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z27.string().max(2e4).optional()}),PublishReleaseResultSchema=z27.object({releaseTag:z27.string(),sha:z27.string(),publishedAt:z27.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z28}from"zod";var AgentSessionStatusSchema,AgentRunStatusSchema,AgentSessionsListQuerySchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_agent_report();init_env();init_create_dto();init_response();init_agent_trigger_dto();init_env_status_dto();AgentSessionStatusSchema=z28.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z28.enum(["in-progress","done","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z28.object({env:z28.string().optional(),project_agents_only:z28.coerce.boolean().optional(),agent_name:z28.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z28.coerce.date().optional(),page:z28.coerce.number().int().positive().default(1),limit:z28.coerce.number().int().positive().max(200).default(25),cursor:z28.coerce.date().optional()}),SessionMetricsSchema=z28.object({cpuMs:z28.number().nonnegative().default(0),netBytes:z28.number().nonnegative().default(0),walltimeMs:z28.number().nonnegative().default(0),llmTokensIn:z28.number().nonnegative().optional(),llmTokensOut:z28.number().nonnegative().optional(),stepCount:z28.number().int().nonnegative().optional(),toolCallCounts:z28.record(z28.string().min(1).max(120),z28.number().int().nonnegative()).optional(),toolCallOutcomes:z28.array(z28.object({toolName:z28.string().min(1).max(120),success:z28.boolean(),code:z28.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z28.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z28.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z28.object({capturedAt:z28.coerce.date(),fingerprint:z28.string().min(1).max(256),counts:z28.object({code:z28.number().int().nonnegative(),content:z28.number().int().nonnegative(),schemas:z28.number().int().nonnegative(),labels:z28.number().int().nonnegative(),assets:z28.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z28.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z28.object({diff:DiffReportSchema,code:z28.array(CodeFileDiffSchema.extend({raw:z28.string().max(24576)})).max(200),schemas:z28.array(SchemaTypeDiffSchema).max(200),content:z28.array(z28.object({key:z28.string().min(1).max(512),collection:z28.string().min(1).max(256),slug:z28.string().max(512).optional(),verb:z28.enum(["added","modified","deleted"]),fields:z28.array(z28.object({name:z28.string().min(1).max(256),before:z28.unknown().optional(),after:z28.unknown().optional()})).max(20)})).max(200),labels:z28.array(z28.object({key:z28.string().min(1).max(512),locale:z28.string().min(1).max(64).optional(),before:z28.unknown().nullable(),after:z28.unknown().nullable()})).max(200),assets:z28.array(z28.object({key:z28.string().min(1).max(512),name:z28.string().min(1).max(512),verb:z28.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z28.object({id:z28.uuid(),projectId:z28.uuid(),env:BranchSchema,agentName:z28.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z28.unknown().optional(),capabilities:z28.array(z28.string()).optional(),dataSources:z28.array(z28.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z28.string().nullable(),startedAt:z28.coerce.date().nullable(),finishedAt:z28.coerce.date().nullable(),cancelledAt:z28.coerce.date().nullable(),costUsd:z28.number().nonnegative(),costCeilingUsd:z28.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z28.boolean(),lastCheckpointId:z28.uuid().nullable(),branchEnvId:z28.uuid().nullable(),parentSessionId:z28.uuid().nullable(),terminalReason:z28.string().nullable(),errorMessage:z28.string().nullable(),reportDocument:StoredReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z28.string().nullable(),createdAt:z28.coerce.date(),updatedAt:z28.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z28.object({id:z28.uuid(),sessionId:z28.uuid(),checkpointIdx:z28.number().int().nonnegative(),payloadRef:z28.string(),payloadSizeBytes:z28.number().int().nonnegative(),checksum:z28.string().length(64),createdAt:z28.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z28.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z28.object({session:AgentSessionDTOSchema,checkpoints:z28.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z28.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=z28.object({reason:z28.string().min(1).max(120).optional()})}});import{z as z29}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=z29.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z29.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z29.object({id:z29.uuid(),envId:z29.uuid(),sessionId:z29.uuid().nullable(),skillName:z29.string().min(1),classification:AgentBranchClassificationSchema,rationale:z29.string().nullable(),summary:z29.string().nullable(),surfaceDeltas:z29.record(z29.string(),z29.unknown()),createdAt:z29.coerce.date(),decidedAt:z29.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z29.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z29.object({path:z29.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z29.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z29.object({code:z29.literal("merge_conflict"),message:z29.string(),conflicts:z29.record(z29.string(),z29.number().int().nonnegative())})}});import{z as z30}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=z30.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z30.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=z30.object({description:z30.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z30.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),threadId:z30.uuid(),invocationId:z30.uuid(),agentKey:z30.string().min(1).max(120),anchorEnv:z30.string().min(1).max(64),retainedEnv:z30.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z30.string().min(1).nullable(),continuationInvocationId:z30.uuid().nullable(),askedAt:z30.coerce.date(),expiresAt:z30.coerce.date(),closedAt:z30.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z30.object({questionId:z30.uuid(),invocationId:z30.uuid(),askedAt:z30.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z30.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z30.object({question:AgentQuestionSchema,continuationInvocationId:z30.uuid(),deduped:z30.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z31}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=z31.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z31.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z31.enum(["secret_text"]),IntegrationCredentialUsageSchema=z31.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z31.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z31.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z31.object({mode:IntegrationAuthModeSchema,label:z31.string().min(1),description:z31.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z31.object({id:z31.string().min(1),label:z31.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z31.boolean()}),IntegrationToolDefinitionDTOSchema=z31.object({key:z31.string().min(1),name:z31.string().min(1),description:z31.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z31.object({title:z31.string().min(1),description:z31.string().min(1),command:z31.string().min(1).optional()}),IntegrationInfoDTOSchema=z31.object({key:z31.string().min(1),name:z31.string().min(1),summary:z31.string().min(1),type:z31.enum(["native","mcp"]).optional(),url:z31.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z31.array(IntegrationAuthModeDTOSchema),credentials:z31.array(IntegrationCredentialDefinitionDTOSchema),tools:z31.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z31.enum(["available","unavailable"]).optional(),recipes:z31.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z31.object({projectId:z31.uuid(),integrationKey:z31.string().min(1),name:z31.string().min(1),summary:z31.string().min(1),installed:z31.boolean(),enabled:z31.boolean(),setupState:z31.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z31.string().nullable(),connectionId:z31.uuid().nullable().optional(),connectionAlias:z31.string().min(1).nullable().optional(),connectionStatus:z31.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z31.array(z31.string()),installedAt:z31.coerce.date().nullable(),updatedAt:z31.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z31.object({id:z31.uuid(),projectId:z31.uuid(),integrationKey:z31.string().min(1),enabled:z31.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z31.string(),connectionId:z31.uuid().nullable().optional(),connectionAlias:z31.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z31.array(z31.string()),createdAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z31.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z31.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z31.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z31.object({value:z31.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z31.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z31.object({id:z31.uuid(),organizationId:z31.string().min(1),integrationKey:z31.string().min(1),alias:z31.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z31.string().min(1),externalAccountName:z31.string().nullable(),externalBotUserId:z31.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z31.array(z31.string()),connectedAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z31.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z31.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z31.record(McpHeaderNameSchema,z31.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z31.object({alias:z31.string().min(1).max(120).optional(),token:z31.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z31.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=z31.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z31.discriminatedUnion("mode",[z31.object({mode:z31.literal("personal"),alias:z31.string().min(1).max(120),token:z31.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z31.boolean().optional()}),z31.object({mode:z31.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z31.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=z31.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z31.union([z31.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z31.object({type:z31.literal("mcp"),name:z31.string().trim().min(1).max(120),url:z31.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z31.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z31.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=z31.object({integrationKey:z31.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z31.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z31.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z31.literal("oauth"),connectUrl:z31.string().url(),expiresAt:z31.coerce.date()})]),ReusableMcpServerAuthKindSchema=z31.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z31.object({id:z31.uuid(),name:z31.string().min(1),host:z31.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z31.string().min(1),availability:z31.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z31.object({query:z31.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z31.object({serverId:z31.uuid()}),StartProjectIntegrationConnectResponseSchema=z31.object({integrationKey:z31.string().min(1),connectUrl:z31.string().url(),expiresAt:z31.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z31.discriminatedUnion("mode",[z31.object({mode:z31.literal("personal"),integrationKey:z31.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z31.object({mode:z31.literal("oauth"),integrationKey:z31.string().min(1),connectUrl:z31.string().url(),expiresAt:z31.coerce.date()})]),BindProjectChannelRequestSchema=z31.object({ref:z31.string().min(1),connectionAlias:z31.string().min(1).optional(),agentName:z31.string().min(1).max(160).nullable().optional(),force:z31.boolean().optional()}),ListProjectChannelsQuerySchema=z31.object({integrationKey:z31.string().min(1)}),SearchProjectChannelsQuerySchema=z31.object({integrationKey:z31.string().min(1),connectionAlias:z31.string().min(1),query:z31.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z31.object({id:z31.uuid(),projectId:z31.uuid(),integrationKey:z31.string().min(1),connectionId:z31.uuid(),externalWorkspaceId:z31.string().min(1),externalChannelId:z31.string().min(1),externalChannelName:z31.string().nullable(),agentName:z31.string().nullable(),enabled:z31.boolean(),createdAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z31.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z31.object({id:z31.string().min(1),name:z31.string().min(1),visibility:z31.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z31.string().min(1).nullable(),canMove:z31.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z31.object({markdown:z31.boolean().optional(),summary:z31.boolean().optional(),links:z31.boolean().optional(),branding:z31.boolean().optional(),images:z31.boolean().optional(),html:z31.union([z31.literal("cleaned"),z31.literal("raw"),z31.boolean()]).optional(),json:z31.union([z31.boolean(),z31.object({prompt:z31.string().min(1).max(1e4),schema:z31.record(z31.string(),z31.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z31.object({url:z31.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional(),waitForMs:z31.number().int().min(0).max(3e4).optional(),maxAgeMs:z31.number().int().min(0).optional(),minAgeMs:z31.number().int().min(0).optional(),storeInCache:z31.boolean().optional(),proxy:z31.enum(["basic","enhanced","auto"]).optional(),mobile:z31.boolean().optional(),location:z31.object({country:z31.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z31.array(z31.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z31.object({query:z31.string().min(1),maxResults:z31.number().int().positive().max(20).optional(),sources:z31.array(z31.enum(["web","news","images"])).min(1).max(3).optional(),categories:z31.array(z31.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z31.enum(["hour","day","week","month","year"]).optional(),location:z31.string().min(1).max(160).optional(),country:z31.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z31.object({query:z31.string().min(1).max(500),maxResults:z31.number().int().min(1).max(100).optional(),types:z31.array(z31.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z31.array(z31.string().min(1).max(512)).min(1).max(20).optional(),sources:z31.array(z31.string().min(1).max(512)).min(1).max(20).optional(),passages:z31.number().int().min(1).max(5).optional(),skills:z31.literal("only").optional(),language:z31.string().min(1).optional(),topic:z31.string().min(1).optional(),license:z31.string().min(1).optional(),minStars:z31.number().int().min(0).optional(),maxStars:z31.number().int().min(0).optional(),archived:z31.boolean().optional(),fork:z31.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z31.object({query:z31.string().min(1).max(500),maxResults:z31.number().int().min(1).max(500).optional(),authors:z31.array(z31.string().min(1)).min(1).optional(),categories:z31.array(z31.string().min(1)).min(1).optional(),from:z31.iso.date().optional(),to:z31.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z31.object({paperId:z31.string().min(1).max(512),query:z31.string().min(1).max(500).optional(),maxPassages:z31.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z31.object({paperId:z31.string().min(1).max(512),intent:z31.string().min(1).max(500),mode:z31.enum(["similar","citers","references"]).optional(),maxResults:z31.number().int().min(1).max(500).optional(),rerank:z31.boolean().optional(),anchors:z31.array(z31.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z31.object({url:z31.string().url(),search:z31.string().min(1).optional(),limit:z31.number().int().positive().max(200).optional(),includeSubdomains:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z31.object({url:z31.string().url(),limit:z31.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z31.object({text:z31.string().min(1).max(200).optional(),cron:z31.string().min(1).max(120).optional(),timezone:z31.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z31.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z31.boolean().optional(),timeoutMs:z31.number().int().positive().max(12e4).optional(),waitForMs:z31.number().int().min(0).max(3e4).optional(),maxAgeMs:z31.number().int().min(0).optional(),minAgeMs:z31.number().int().min(0).optional(),storeInCache:z31.boolean().optional(),proxy:z31.enum(["basic","enhanced","auto"]).optional(),mobile:z31.boolean().optional(),location:z31.object({country:z31.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z31.array(z31.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z31.union([z31.object({type:z31.enum(["scrape","crawl"]).default("scrape"),urls:z31.array(z31.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z31.object({type:z31.literal("search"),queries:z31.array(z31.string().min(1).max(256)).min(1).max(12),searchWindow:z31.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z31.number().int().min(1).max(50).optional(),includeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z31.array(z31.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z31.object({name:z31.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z31.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z31.string().min(1).max(2e3).optional(),judgeEnabled:z31.boolean().optional(),retentionDays:z31.number().int().min(1).max(365).optional(),notification:z31.object({email:z31.object({enabled:z31.boolean().default(!0),recipients:z31.array(z31.string().email()).min(1).max(20),includeDiffs:z31.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=z31.object({monitorId:z31.string().uuid(),name:z31.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z31.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z31.string().min(1).max(2e3).optional(),judgeEnabled:z31.boolean().optional(),retentionDays:z31.number().int().min(1).max(365).optional(),status:z31.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z31.object({monitorId:z31.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z31.string().uuid()}),RunProjectIntegrationToolRequestSchema=z31.object({tool:z31.string().min(1),input:z31.record(z31.string(),z31.unknown()),connectionAlias:z31.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z31.object({provider:z31.string().min(1),providerCredits:z31.number().nonnegative().optional(),providerCostUsd:z31.number().nonnegative().optional(),requests:z31.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z31.object({credits:z31.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z31.object({url:z31.string(),provider:z31.literal("firecrawl"),title:z31.string().optional(),statusCode:z31.number().optional(),markdown:z31.string().optional(),summary:z31.string().optional(),links:z31.array(z31.string()).optional(),images:z31.array(z31.string()).optional(),html:z31.string().optional(),json:z31.unknown().optional(),branding:z31.record(z31.string(),z31.unknown()).optional(),warning:z31.string().optional()}),FirecrawlSearchToolOutputSchema=z31.object({query:z31.string(),provider:z31.literal("firecrawl"),warning:z31.string().optional(),results:z31.array(z31.object({title:z31.string(),url:z31.string(),snippet:z31.string().optional(),content:z31.string().optional(),score:z31.number().optional(),publishedAt:z31.string().optional()}))}),FirecrawlResearchPaperSchema=z31.object({paperId:z31.string(),primaryId:z31.string().optional(),ids:z31.record(z31.string(),z31.array(z31.string())).optional(),title:z31.string().optional(),abstract:z31.string().optional(),score:z31.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z31.object({text:z31.string(),score:z31.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),results:z31.array(z31.object({id:z31.string(),type:z31.string().min(1).optional(),url:z31.string(),title:z31.string().optional(),passages:z31.array(z31.object({text:z31.string()}).passthrough())}).passthrough()),coverage:z31.record(z31.string(),z31.string()).optional(),reranked:z31.boolean().optional(),repos:z31.array(z31.record(z31.string(),z31.unknown())).optional(),sources:z31.array(z31.record(z31.string(),z31.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),results:z31.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),paper:z31.record(z31.string(),z31.unknown()),paperId:z31.string().optional(),query:z31.string().optional(),passages:z31.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),results:z31.array(FirecrawlResearchPaperSchema),poolSize:z31.number().int().nonnegative(),truncated:z31.boolean(),note:z31.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z31.object({url:z31.string(),provider:z31.literal("firecrawl"),count:z31.number(),links:z31.array(z31.object({url:z31.string(),title:z31.string().optional(),description:z31.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z31.object({url:z31.string(),provider:z31.literal("firecrawl"),total:z31.number(),pages:z31.array(z31.object({url:z31.string(),title:z31.string().optional(),statusCode:z31.number().optional(),markdown:z31.string().optional(),summary:z31.string().optional(),links:z31.array(z31.string()).optional(),images:z31.array(z31.string()).optional(),html:z31.string().optional(),warning:z31.string().optional()})),warning:z31.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z31.object({cron:z31.string().optional(),text:z31.string().optional(),timezone:z31.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z31.object({id:z31.string().optional(),type:z31.enum(["scrape","crawl","search"]).optional(),urls:z31.array(z31.string()).optional(),queries:z31.array(z31.string()).optional(),searchWindow:z31.string().optional(),maxResults:z31.number().optional(),includeDomains:z31.array(z31.string()).optional(),excludeDomains:z31.array(z31.string()).optional(),scrapeOptions:z31.record(z31.string(),z31.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z31.object({id:z31.string(),name:z31.string(),status:z31.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z31.string().nullable().optional(),lastRunAt:z31.string().nullable().optional(),currentCheckId:z31.string().nullable().optional(),targets:z31.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z31.string().nullable().optional(),judgeEnabled:z31.boolean().optional(),estimatedCreditsPerMonth:z31.number().optional(),createdAt:z31.string().optional(),updatedAt:z31.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z31.object({id:z31.string(),monitorId:z31.string(),scheduledFor:z31.string().nullable().optional(),startedAt:z31.string().nullable().optional(),finishedAt:z31.string().nullable().optional(),estimatedCredits:z31.number().optional(),reservedCredits:z31.number().optional(),actualCredits:z31.number().optional(),billingStatus:z31.string().nullable().optional(),summary:z31.object({totalPages:z31.number().optional(),same:z31.number().optional(),changed:z31.number().optional(),new:z31.number().optional(),removed:z31.number().optional(),error:z31.number().optional()}).passthrough().optional(),error:z31.string().nullable().optional(),createdAt:z31.string().optional(),updatedAt:z31.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitors:z31.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitorId:z31.string(),deleted:z31.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitorId:z31.string(),checks:z31.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z31.object({provider:z31.literal("firecrawl"),monitorId:z31.string(),check:FirecrawlMonitorCheckOutputSchema,next:z31.string().optional()}),FirecrawlToolKeySchema=z31.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=z31.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z31.object({projectId:z31.uuid(),integrationKey:z31.string().min(1),tool:z31.string().min(1),connectionAlias:z31.string().min(1).nullable().optional(),output:z31.record(z31.string(),z31.unknown()),executedAt:z31.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z31.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z31.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z31.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z31.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z31.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z31.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z31.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z31.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z31.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z31.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z31.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z31.array(ProjectChannelCandidateDTOSchema))}});import{z as z32}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=z32.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z32.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z32.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z32.object({userId:z32.string().min(1),name:z32.string(),email:z32.string().min(1),subscribed:z32.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z32.object({maxSubscribers:z32.number().int().positive(),subscriberCount:z32.number().int().nonnegative(),effectiveRecipientCount:z32.number().int().nonnegative(),currentUserSubscribed:z32.boolean(),candidates:z32.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z32.object({userIds:z32.array(z32.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z32.object({topic:UserManagedNotificationTopicSchema,enabled:z32.boolean(),source:z32.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z32.object({topics:z32.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z32.object({enabled:z32.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z32.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z32.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z32.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z32.string().nullable(),maskedEmail:z32.string().min(1),applied:z32.boolean(),expiresAt:z32.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z32.object({scheduleId:z32.string().min(1),scheduleName:z32.string(),projectId:z32.string().min(1),projectName:z32.string(),env:z32.string().min(1)}),FollowedSchedulesSchema=z32.object({schedules:z32.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z33}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=z33.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=z33.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z33.uuid(),env:z33.string().min(1),name:z33.string().min(1),cron:z33.string().min(1),command:z33.string().min(1),secretKeys:z33.array(z33.string().min(1)),enabled:z33.boolean(),lastRunAt:z33.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z33.string().nullable(),overPolicyReasons:z33.array(z33.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z33.object({name:z33.string().min(1).max(120),cron:z33.string().min(1).max(120),command:z33.string().min(1).max(500),secretKeys:z33.array(ProjectSecretKeySchema).default([]),enabled:z33.boolean().optional()}),UpdateProjectScheduleRequestSchema=z33.object({name:z33.string().min(1).max(120).optional(),cron:z33.string().min(1).max(120).optional(),command:z33.string().min(1).max(500).optional(),secretKeys:z33.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z33.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z33.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z33.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z33.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z33.object({maxRuns:z33.number().int().positive(),retentionDays:z33.number().int().positive().nullable(),outputRetentionDays:z33.number().int().positive(),maxOutputBytes:z33.number().int().positive()}),SchedulePolicyStateSchema=z33.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z33.object({code:z33.enum(["Free","Premium","Pro"]),source:z33.enum(["cached_subscription","free_fallback"]),activeSchedules:z33.object({used:z33.number().int().nonnegative(),limit:z33.number().int().positive()}),minCadenceMinutes:z33.number().int().positive(),maxRunMs:z33.number().int().positive(),concurrency:z33.object({used:z33.number().int().nonnegative(),limit:z33.number().int().positive()}),compute:z33.object({settledMs:z33.number().int().nonnegative(),reservedMs:z33.number().int().nonnegative(),includedMs:z33.number().int().positive(),remainingMs:z33.number().int().nonnegative(),resetsAt:z33.coerce.date()}),upgrade:z33.object({code:z33.literal("Pro"),activeSchedulesLimit:z33.number().int().positive(),minCadenceMinutes:z33.number().int().positive(),maxRunMs:z33.number().int().positive(),maxConcurrentRuns:z33.number().int().positive(),computeIncludedMs:z33.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z33.array(z33.string())}),ProjectScheduleUsageSchema=z33.object({runCount:z33.number().int().nonnegative(),runsWithOutput:z33.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z33.object({id:z33.uuid(),scheduleId:z33.uuid(),projectId:z33.uuid(),env:z33.string().min(1),scheduleName:z33.string().min(1),command:z33.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z33.object({id:z33.string().min(1),name:z33.string().min(1)}).nullable(),queuedAt:z33.coerce.date(),startedAt:z33.coerce.date().nullable(),finishedAt:z33.coerce.date().nullable(),exitCode:z33.number().int().nullable(),errorCode:z33.string().nullable(),error:z33.string().nullable(),outputBytes:z33.number().int().nonnegative(),outputTruncated:z33.boolean(),outputExpiresAt:z33.coerce.date().nullable(),metadataExpiresAt:z33.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z33.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z33.coerce.date().nullable(),items:z33.array(z33.object({key:z33.string().min(1),updatedAt:z33.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z33.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z33.object({trigger:z33.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z33.object({limit:z33.coerce.number().int().min(1).max(100).default(25),cursor:z33.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z33.object({items:z33.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z33.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z33.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z33.object({items:z33.array(ProjectScheduleRunDTOSchema),nextCursor:z33.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z34}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,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_agent_report();init_response();WORK_NOTIFICATION_TOPICS=["agent_question","agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z34.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z34.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z34.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z34.discriminatedUnion("kind",[z34.object({kind:z34.literal("user"),userId:z34.string().min(1)}).strict(),z34.object({kind:z34.literal("agent"),agentKey:z34.string().min(1).max(120),agentId:z34.uuid().optional()}).strict(),z34.object({kind:z34.literal("system")}).strict()]),NotificationSummarySchema=z34.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z34.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z34.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z34.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z34.discriminatedUnion("topic",[z34.object({topic:z34.literal("agent_question"),questionId:z34.uuid(),title:z34.string().trim().min(1).max(80),description:z34.string().trim().min(1).max(240)}).strict(),z34.object({topic:z34.literal("agent_run_outcome"),threadId:z34.uuid(),invocationId:z34.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z34.object({topic:z34.literal("agent_retained_review"),threadId:z34.uuid(),invocationId:z34.uuid().optional(),proposalId:z34.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z34.object({topic:z34.literal("agent_conflict"),mergeId:z34.uuid(),threadId:z34.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z34.object({id:z34.uuid(),projectId:z34.uuid(),sourceKey:z34.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z34.literal(1),payload:NotificationPayloadSchema,createdAt:z34.coerce.date()}),NotificationRecipientStateSchema=z34.object({id:z34.uuid(),notificationId:z34.uuid(),projectId:z34.uuid(),userId:z34.string().min(1),readAt:z34.coerce.date().nullable(),archivedAt:z34.coerce.date().nullable(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),NotificationDeliveryStateSchema=z34.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z34.object({id:z34.uuid(),notificationRecipientId:z34.uuid(),projectId:z34.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z34.number().int().nonnegative(),nextAttemptAt:z34.coerce.date().nullable(),lastAttemptAt:z34.coerce.date().nullable(),sentAt:z34.coerce.date().nullable(),failureCode:z34.string().max(80).nullable(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),NotificationPreferenceSchema=z34.object({topic:WorkNotificationTopicSchema,channel:z34.literal("email"),enabled:z34.boolean(),source:z34.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z34.object({topics:z34.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z34.discriminatedUnion("kind",[z34.object({kind:z34.literal("question"),questionId:z34.uuid()}).strict(),z34.object({kind:z34.literal("run_outcome"),threadId:z34.uuid(),invocationId:z34.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z34.object({kind:z34.literal("retained_review"),threadId:z34.uuid(),invocationId:z34.uuid().nullable(),proposalId:z34.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z34.object({kind:z34.literal("merge_conflict"),mergeId:z34.uuid(),threadId:z34.uuid().nullable()}).strict()]),NotificationViewSchema=z34.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z34.object({items:z34.array(NotificationViewSchema),nextCursor:z34.string().nullable(),unreadCount:z34.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z34.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z34.string().min(1).max(120).optional(),sourceKey:z34.string().min(1).max(255).optional(),unread:z34.stringbool().optional(),archived:z34.stringbool().optional(),limit:z34.coerce.number().int().min(1).max(100).optional(),cursor:z34.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=z34.object({recipient:NotificationRecipientStateSchema,unreadCount:z34.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z34.object({read:z34.boolean().optional(),archived:z34.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z35}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=z35.object({surface:SurfaceNameSchema,key:z35.string(),label:z35.string()}),InlineSchema=z35.object({text:z35.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z35.discriminatedUnion("type",[z35.object({type:z35.literal("paragraph"),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("preview"),ref:DiffRefSchema,caption:z35.string().optional()}),z35.object({type:z35.literal("code"),code:z35.string(),lang:z35.string().optional(),caption:z35.string().optional()}),z35.object({type:z35.literal("risk"),level:z35.enum(["warning","error"]),content:z35.array(InlineSchema).max(24)}),z35.object({type:z35.literal("list"),items:z35.array(z35.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z35.object({headline:z35.string(),blocks:z35.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z35.object({summary:EnvDiffSummarySchema,fingerprint:z35.string(),generatedAt:z35.coerce.date(),cached:z35.boolean().optional(),credits:z35.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z36}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=z36.object({date:z36.string(),visitors:z36.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z36.object({key:z36.string(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z36.object({path:z36.string(),pageName:z36.string().nullable().optional(),visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z36.object({preset:z36.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z36.string(),requestedTo:z36.string(),effectiveFrom:z36.string(),effectiveTo:z36.string(),isRetentionLimited:z36.boolean(),groupBy:z36.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z36.object({date:z36.string(),content:z36.string(),updatedAt:z36.string(),updatedByUserId:z36.string()}),ProjectPageviewAnalyticsDTOSchema=z36.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z36.number().int().nonnegative(),pageviews:z36.number().int().nonnegative(),bounceRate:z36.number().min(0).max(100),viewsPerVisit:z36.number().nonnegative(),averageVisitDurationSeconds:z36.number().nonnegative(),visitorsSeries:z36.array(ProjectDailyVisitorsDTOSchema),topPages:z36.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z36.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z36.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z37}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=z37.object({id:z37.string(),email:z37.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z37.coerce.date(),createdAt:z37.coerce.date(),inviterUserId:z37.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z37.object({id:z37.string(),token:z37.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z37.object({success:z37.boolean(),projectId:z37.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z38}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=z38.object({id:z38.string(),name:z38.string(),image:z38.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z38.object({count:z38.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z38.object({counts:z38.object({signed_up:z38.int(),activated:z38.int()}),credits:z38.object({total:z38.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z38.email(),emailVerified:z38.boolean(),createdAt:z38.coerce.date(),updatedAt:z38.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z39}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=z39.object({id:z39.string(),principalType:ProjectPrincipalTypeSchema,principalId:z39.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z39.coerce.date(),expiresAt:z39.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=z39.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z39.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z39.record(z39.string(),z39.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z39.object({access:z39.array(ProjectAccessItemDTOSchema),invites:z39.array(ProjectInviteDTOSchema),organization:z39.object({name:z39.string().nullable(),logo:z39.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z39.object({success:z39.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z39.object({success:z39.boolean(),projectId:z39.uuid()}))}});import{z as z40}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=z40.object({publicationStatus:PublicationStatusSchema,appUrl:z40.string().nullable(),lastPublishedAt:z40.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z41}from"zod";var PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,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();PreviewBridgePackageSchema=z41.object({name:z41.string().min(1),version:z41.string().min(1)}),PreviewBridgeCapabilitySchema=z41.object({integrated:z41.boolean(),packages:z41.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z41.object({url:z41.url(),expiresAt:z41.iso.datetime(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z41.object({name:z41.string().min(1),locator:z41.string().min(1).optional(),source:z41.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z41.object({kind:z41.literal("dependency_build_scripts_blocked"),packageManager:z41.enum(["pnpm","yarn","bun"]),packages:z41.array(z41.string()),targets:z41.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z41.string(),approvalKey:z41.string(),command:z41.string().optional(),approval:z41.object({id:z41.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z41.object({code:z41.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z41.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z41.object({approvalId:z41.uuid()}),PreviewInstallPolicyApprovalEventSchema=z41.discriminatedUnion("type",[z41.object({type:z41.literal("progress"),step:z41.enum(["approval","install","restart","readiness"]),message:z41.string()}),z41.object({type:z41.literal("approved")}),z41.object({type:z41.literal("complete")}),z41.object({type:z41.literal("error"),code:z41.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z41.string()})])}});import{z as z42}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:z42.string(),slug:z42.string().nullable(),logo:z42.string().nullable(),metadata:z42.record(z42.string(),z42.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z42.object({id:z42.string(),name:z42.string(),email:z42.email(),image:z42.string().nullable()}),OrganizationMemberDTOSchema=z42.object({id:z42.string(),userId:z42.string(),organizationId:z42.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z42.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z43}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,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=z43.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z43.object({reason:CancellationReasonCodeSchema,details:z43.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z43.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z43.object({offerVersion:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),renewsOn:z43.string()}),PlanMigrationPreviewDTOSchema=z43.object({currency:z43.string().trim().min(1),unusedPremiumCreditAmount:z43.number().int().nonnegative(),amountDueNow:z43.number().int().nonnegative(),startsAt:z43.string(),renewsAt:z43.string(),nextRenewalAmount:z43.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z43.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z43.object({id:z43.string(),organizationId:z43.string(),legacySubscriptionId:z43.string(),offeredPlanCode:z43.string(),offeredPlanName:z43.string(),offeredPriceAmount:z43.number(),offeredCurrency:z43.string(),offerVersion:z43.string(),state:PlanMigrationStateSchema,checkoutToken:z43.string().nullable(),deadlineAt:z43.string(),transitions:z43.array(z43.object({event:z43.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z43.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z43.object({included:z43.number().optional(),unitPrice:z43.number().optional(),dailyCap:z43.number().nullable().optional()}),EntitlementsDTOSchema=z43.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z43.object({retentionDays:z43.number().int().positive(),canUseExtendedDateRanges:z43.boolean()}).optional(),history:z43.object({retentionDays:z43.number().int().positive()}).optional(),members:z43.object({canInvite:z43.boolean(),maxMembers:z43.number().int().positive().nullable()}).optional(),domains:z43.object({canUseCustomDomains:z43.boolean(),maxDomains:z43.number().int().nonnegative().nullable()}).optional(),media_storage:z43.object({limitBytes:z43.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z43.object({usedBytes:z43.number().int().nonnegative().nullable(),limitBytes:z43.number().int().nonnegative().nullable(),state:z43.enum(["ready","unavailable"]),measuredAt:z43.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),SubscriptionDTOSchema=z43.object({id:z43.string(),external_id:z43.string(),customerId:z43.string(),planId:z43.string(),planCode:z43.union([TemplateCodeSchema,z43.literal("Unknown")]),currentPeriod:z43.object({start:z43.string(),end:z43.string().nullable()}),cancelAt:z43.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z43.string(),nextPaymentAt:z43.string().nullable(),baseAmount:z43.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z43.object({totalCap:z43.number(),dailyCap:z43.number(),usedTotal:z43.number()}),CreditBalanceDTOSchema=z43.object({total:z43.number(),base:z43.number(),dailyBase:z43.number(),purchases:z43.number(),awards:z43.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z43.object({total:z43.number(),nearLimit:z43.boolean(),canChat:z43.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z43.object({dailyFreeAvailable:z43.number(),monthlyAvailable:z43.number(),purchasedAvailable:z43.number(),awardedAvailable:z43.number()}),ProjectDailyCreditAllowanceDTOSchema=z43.object({periodCap:z43.number(),dailyGrant:z43.number(),usedThisPeriod:z43.number(),remainingThisPeriod:z43.number()}),ProjectCreditBalanceDTOSchema=z43.object({projectId:z43.uuid(),organizationId:z43.string(),balance:z43.object({totalAvailable:z43.number(),nearLimit:z43.boolean(),canUseAi:z43.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z43.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z43.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z43.object({planCode:z43.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z43.object({source:z43.enum(["cached_subscription","free_fallback"]),settledMs:z43.number().int().nonnegative(),reservedMs:z43.number().int().nonnegative(),includedMs:z43.number().int().positive(),remainingMs:z43.number().int().nonnegative(),resetsAt:z43.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().nonnegative(),refillAmountUsd:z43.number().nonnegative()}),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().nonnegative().nullable(),refillAmountUsd:z43.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z43.discriminatedUnion("enabled",[z43.object({enabled:z43.literal(!0),thresholdUsd:z43.number().min(.01).multipleOf(.01),refillAmountUsd:z43.number().min(.01).multipleOf(.01)}).strict(),z43.object({enabled:z43.literal(!1),thresholdUsd:z43.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z43.object({invoiceId:z43.string(),newBalance:z43.int(),creditCount:z43.int(),amountUsd:z43.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z43.object({url:z43.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 z44}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=z44.object({brand:z44.string(),last4:z44.string(),exp:z44.string(),isDefault:z44.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z45}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=z45.string().superRefine((path53,ctx)=>{let segments=path53.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z45.object({type:z45.literal("renameField"),contentType:z45.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z45.object({enabled:z45.boolean()}).strict(),ContentFieldGroupSchema=z45.object({id:z45.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z45.string().min(1).max(255),default:z45.boolean().optional()}).strict(),ContentTypeDTOSchema=z45.object({id:z45.string(),name:z45.string(),label:z45.string(),isSingleton:z45.boolean(),i18n:ContentTypeI18nSchema,groups:z45.array(ContentFieldGroupSchema).default([]),fields:z45.record(z45.string(),FieldDefinitionSchema),createdAt:z45.string(),updatedAt:z45.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z45.object({contentTypes:z45.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z45.object({id:z45.string(),entryId:z45.string(),documentId:z45.string(),slug:z45.string(),locale:z45.string().optional(),createdAt:z45.string(),updatedAt:z45.string(),__fimo:z45.object({contentType:z45.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({limit:z45.number(),offset:z45.number(),total:z45.number(),hasMore:z45.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z45.object({contentType:z45.string(),count:z45.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z45.object({counts:z45.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z45.object({count:z45.number().int().nonnegative(),sourceLocale:z45.string(),targetLocale:z45.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z45.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z45.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z45.union([z45.string(),z45.number(),z45.boolean(),z45.null()]),entryWhereOperatorSchema=z45.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z45.array(entryWhereScalarSchema).optional(),$nin:z45.array(entryWhereScalarSchema).optional(),$contains:z45.string().optional(),$startsWith:z45.string().optional(),$null:z45.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z45.record(z45.string(),z45.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z45.object({data:z45.record(z45.string(),z45.unknown()),locale:z45.string().min(1).optional(),documentId:z45.uuid().optional()}),entryIdsSchema=z45.array(z45.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z45.object({sql:z45.string().min(1)}),BulkCreateEntriesRequestSchema=z45.object({entries:z45.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z45.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z45.object({updates:z45.array(z45.object({id:z45.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z45.union([z45.object({ids:entryIdsSchema,locale:z45.string().min(1).optional()}),z45.object({where:EntryWhereSchema,locale:z45.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z45.object({data:z45.array(z45.record(z45.string(),z45.unknown())),meta:z45.object({rowCount:z45.number().int().nonnegative(),truncated:z45.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({created:z45.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({updated:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z45.object({data:z45.array(EntryDTOSchema),meta:z45.object({deleted:z45.number().int().nonnegative(),missing:z45.array(z45.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z46}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z46.object({index:z46.number().int().nonnegative(),contentType:z46.string(),field:z46.string(),value:z46.string(),against:z46.enum(["stored","batch"]),ownerDocumentId:z46.uuid().optional(),ownerIndex:z46.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z46.object({code:z46.literal("unique_conflict"),message:z46.string(),conflicts:z46.array(UniqueConflictSchema),truncated:z46.boolean().optional()})}});import{z as z47}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=z47.object({kind:z47.literal("unique_conflict"),contentType:z47.string(),field:z47.string(),value:z47.string(),documentCount:z47.number().int().positive(),documentIds:z47.array(z47.uuid()),documentIdsTruncated:z47.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z47.object({code:z47.literal("schema_transition_rejected"),message:z47.string(),issues:z47.array(SchemaTransitionIssueSchema),truncated:z47.boolean().optional()})}});import{z as z48}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=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z48.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z48.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z48.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z48.object({field:CmsFieldNameSchema,direction:z48.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z48.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z48.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z48.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z48.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z48.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z49}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z49.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z50}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z50.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z50.object({event:ClientTrackedEventSchema,properties:z50.record(z50.string(),z50.unknown()).default({})})}});import{z as z51}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z51.object({id:z51.string(),name:z51.string()}),AssetDTOSchema=z51.object({id:z51.string(),name:z51.string(),type:AssetTypeSchema,originalFileName:z51.string().nullable(),parentId:z51.string().nullable(),mimeType:z51.string().nullable(),fileSize:z51.number().nullable(),url:z51.string().nullable(),storageKey:z51.string().nullable(),createdAt:z51.string(),updatedAt:z51.string(),altText:z51.string().nullable().optional(),caption:z51.string().nullable().optional(),aiCaption:z51.string().nullable().optional(),aiAltText:z51.string().nullable().optional(),aiTags:z51.array(z51.string()).nullable().optional(),aiPrimaryColor:z51.string().nullable().optional(),aiProcessingStatus:z51.string().nullable().optional(),width:z51.number().nullable().optional(),height:z51.number().nullable().optional(),path:z51.array(AssetPathItemSchema).optional(),hasChildren:z51.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z51.lazy(()=>z51.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z51.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z51.object({error:z51.string(),code:z51.literal("media_storage_limit_exceeded"),usedBytes:z51.number().int().nonnegative(),limitBytes:z51.number().int().positive(),incomingBytes:z51.number().int().nonnegative()}),AssetReferenceScopeSchema=z51.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z51.object({assetIds:z51.array(z51.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z51.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z51.object({totalFiles:z51.number().int().nonnegative(),checkedFiles:z51.number().int().nonnegative(),limit:z51.number().int().positive()}),AssetReferenceFindingDTOSchema=z51.object({assetId:z51.uuid(),entryId:z51.string(),documentId:z51.string(),contentType:z51.string(),locale:z51.string().nullable(),slug:z51.string(),fieldPath:z51.string()}),AssetReferenceScopeResultDTOSchema=z51.object({scope:AssetReferenceScopeSchema,label:z51.string(),state:z51.enum(["available","not-published","failed"]),coverage:z51.enum(["complete","partial","failed"]),referenceCount:z51.number().int().nonnegative().optional(),codeReferenceCount:z51.number().int().nonnegative().optional(),referencedAssetIds:z51.array(z51.uuid()).optional(),references:z51.array(AssetReferenceFindingDTOSchema),reason:z51.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z51.discriminatedUnion("type",[z51.object({type:z51.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z51.object({type:z51.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z51.object({type:z51.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z51.object({replacementAssetId:z51.uuid()}),AssetReferenceReplacementResultSchema=z51.object({referencesReplaced:z51.number().int().nonnegative(),entriesChanged:z51.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z51.object({referencesReplaced:z51.number().int().nonnegative(),filesChanged:z51.number().int().nonnegative(),commitSha:z51.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z51.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z51.object({error:z51.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z51.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z51.object({intent:AssetRemovalIntentSchema,assetIds:z51.array(z51.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z51.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z51.object({id:z51.uuid(),intent:AssetRemovalIntentSchema,assetIds:z51.array(z51.uuid()),replacementAssetId:z51.uuid().nullable(),expiresAt:z51.iso.datetime(),undoable:z51.boolean(),requestedByMe:z51.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z51.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z51.object({error:z51.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z52}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z52.object({key:z52.string(),value:z52.string().optional(),defaultValue:z52.string(),locale:z52.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z53}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=z53.object({id:z53.string(),name:z53.string(),type:z53.enum(["file","folder"]),path:z53.string(),children:z53.lazy(()=>z53.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z53.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z53.object({path:z53.string(),exists:z53.boolean(),type:z53.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z54}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=z54.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z54.object({items:z54.array(ProjectMessagePublicDTOSchema),nextCursor:z54.string().nullable()}),ChatLiveTurnDTOSchema=z54.object({invocationId:z54.string(),step:z54.enum(["preparing","working","compacting","merging"]),startedAt:z54.string()}),ChatLiveTurnStateDTOSchema=z54.object({threadId:z54.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z54.object({id:z54.string(),role:z54.enum(["user","assistant"]),parts:z54.array(z54.unknown()),metadata:z54.record(z54.string(),z54.unknown()).nullable(),versionId:z54.string().nullable().optional(),createdAt:z54.date().transform(value=>value.toISOString()),providerMessageId:z54.string().nullable().optional(),invocationId:z54.string().nullable().optional(),invocationStatus:z54.string().nullable().optional(),invocationTerminalReason:z54.string().nullable().optional()}),ChatAttentionDTOSchema=z54.object({type:z54.literal("merge_conflict"),merge:z54.object({mergeId:z54.string().uuid(),projectId:z54.string(),fromEnv:z54.string(),toEnv:z54.string()}),publishAfterMerge:z54.boolean()}),ChatThreadMessagesPageDTOSchema=z54.object({threadId:z54.string().nullable(),title:z54.string().nullable(),messages:z54.array(ChatThreadMessageDTOSchema),nextCursor:z54.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z54.object({kind:z54.literal("replay"),threadId:z54.string(),userMessageId:z54.string()}),ChatQueuedOutcomeDTOSchema=z54.object({kind:z54.literal("queued"),threadId:z54.string(),userMessageId:z54.string(),blockingRootId:z54.string()}),ChatBusyOutcomeDTOSchema=z54.object({kind:z54.literal("busy"),threadId:z54.string(),userMessageId:z54.string(),blockingRootId:z54.string().optional()}),ChatRefusedOutcomeDTOSchema=z54.object({kind:z54.literal("refused"),threadId:z54.string(),userMessageId:z54.string(),refusedInvocationId:z54.string(),terminalReason:z54.string()}),ChatNonStreamingOutcomeDTOSchema=z54.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z54.object({success:z54.boolean(),deletedCount:z54.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z54.object({code:z54.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z54.string()})}});import{z as z55}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=z55.object({url:z55.string().url(),key:z55.string(),size:z55.number(),contentType:z55.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z56}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=z56.object({canAccess:z56.boolean(),permissions:z56.record(z56.string(),z56.boolean()),role:z56.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z57}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:z57.string().trim().default(""),sort:z57.enum(["recent","name","relevance"]).default("recent"),category:z57.string().optional()})}});import{z as z58}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=z58.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z58.enum(["fimo","external"]),PaymentStatusSchema=z58.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z58.object({id:z58.string().uuid(),domain:z58.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z58.boolean(),price:z58.number().int().nullable(),renewalPrice:z58.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z58.string().nullable(),failureReason:z58.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z58.object({domain:z58.string(),available:z58.boolean(),premium:z58.boolean(),price:z58.number().nullable(),renewalPrice:z58.number().nullable(),purchaseType:z58.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z58.object({domain:z58.string(),price:z58.number().nullable(),renewalPrice:z58.number().nullable(),premium:z58.boolean(),allowedYears:z58.array(z58.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z58.object({firstName:z58.string().max(100),lastName:z58.string().max(100),companyName:z58.string().max(100).optional(),address1:z58.string().max(255),address2:z58.string().max(255).optional(),city:z58.string().max(100),state:z58.string().max(100),zip:z58.string().max(20),country:z58.string().max(2),phone:z58.string().max(30),email:z58.union([z58.string().email().max(255),z58.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z58.object({firstName:z58.string().min(1).max(100),lastName:z58.string().min(1).max(100),companyName:z58.string().max(100).optional(),address1:z58.string().min(1).max(255),address2:z58.string().max(255).optional(),city:z58.string().min(1).max(100),state:z58.string().min(1).max(100),zip:z58.string().min(1).max(20),country:z58.string().min(1).max(2),phone:z58.string().min(1).max(30),email:z58.string().email().max(255)}),SearchDomainsRequestSchema=z58.object({keyword:z58.string().min(1).max(100),tldFilter:z58.array(z58.string()).optional()}),CheckAvailabilityRequestSchema=z58.object({domains:z58.array(z58.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=z58.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z58.object({domain:DomainNameSchema,years:z58.number().int().min(1).max(10).optional().default(3),autoRenew:z58.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z58.object({autoRenew:z58.boolean().optional()}),RenewDomainRequestSchema=z58.object({years:z58.number().int().min(1).max(10).optional().default(1),autoRenew:z58.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z58.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z58.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z58.object({verified:z58.boolean(),email:z58.string().nullable(),verifyBy:z58.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z59}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=z59.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=z59.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=z59.object({txtName:z59.string().nullable().optional(),txtValue:z59.string().nullable().optional(),httpUrl:z59.string().nullable().optional(),httpBody:z59.string().nullable().optional(),cname:z59.string().nullable().optional(),cnameTarget:z59.string().nullable().optional()}),SSLValidationErrorSchema=z59.object({message:z59.string()}),OwnershipVerificationSchema=z59.object({type:z59.string(),name:z59.string(),value:z59.string()}),ProjectDomainSSLDTOSchema=z59.object({status:z59.string(),method:z59.string().nullable(),type:z59.string().nullable(),validationRecords:z59.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z59.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z59.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z59.enum(["subdomain","apex"]),RedirectConfigSchema=z59.object({type:z59.literal("apex_to_www"),linkedDomainId:z59.string()}).nullable().optional(),ProjectDomainDTOSchema=z59.object({id:z59.string(),hostname:z59.string(),status:z59.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z59.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z59.string(),scdCnameTarget:z59.string().optional(),apexTargets:z59.array(z59.string()),dnsAutoConfigured:z59.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z59.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z59.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z59.object({hostname:z59.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:z59.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z59.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z59.object({available:z59.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z59.object({success:z59.boolean(),hostname:z59.string()}))}});import{z as z60}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=z60.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z60.object({available:z60.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z60.object({slug:z60.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z60.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z60.object({subdomain:z60.string(),subdomainUpdatedAt:z60.coerce.date()})),SubdomainSuggestionsQuerySchema=z60.object({base:z60.string().max(100).optional(),max:z60.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z60.object({suggestions:z60.array(z60.string())}))}});import{z as z61}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=z61.object({translated:z61.number().int().nonnegative(),total:z61.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z61.object({locale:z61.string(),isDefault:z61.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z61.object({defaultLocale:z61.string(),locales:z61.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z61.object({locale:z61.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z61.object({locale:z61.string().min(1).max(40)}),ProjectLocaleMutationSchema=z61.object({locale:z61.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z61.object({locale:z61.string(),entriesDeleted:z61.number().int().nonnegative(),labelsDeleted:z61.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z62}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=z62.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z62.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=z62.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z62.number(),credits:z62.number().optional(),billingMode:z62.enum(["fimo-credits","provider-account"]).optional(),confidence:z62.enum(["exact","estimated","metered"]),basis:z62.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z63}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=z63.object({options:z63.record(z63.string(),z63.unknown()),name:z63.string().optional(),parentId:z63.string().nullable().optional(),altText:z63.string().optional(),caption:z63.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z63.string().min(1).optional(),model:z63.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=z63.object({jobId:z63.string(),status:z63.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z63.string().nullable().optional(),credits:z63.number().optional(),costUsd:z63.number().optional(),billingMode:z63.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z63.object({error:z63.string(),code:z63.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:z63.array(GenerationTaskIdSchema).optional(),availableModels:z63.array(z63.string()).optional(),issues:z63.array(z63.unknown()).optional()})}});import{z as z64}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=z64.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z64.object({name:z64.string(),key:z64.string(),description:z64.string(),type:FlagTypeSchema,required:z64.boolean(),defaultValue:z64.unknown().optional(),enumValues:z64.array(z64.string()).optional(),isArray:z64.boolean()}),AssetModelPriceSchema=z64.object({unitPrice:z64.number(),unit:z64.string(),confidence:z64.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z64.object({id:z64.string(),shortName:z64.string(),provider:z64.string(),source:z64.string(),modality:z64.enum(["image","video","audio"]),tags:z64.array(z64.string()),displayName:z64.string(),description:z64.string(),flags:z64.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z64.object({model:z64.string(),costUsd:z64.number(),credits:z64.number(),billingMode:z64.enum(["fimo-credits","provider-account"]),confidence:z64.enum(["exact","estimated","metered"]),basis:z64.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z65}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=z65.object({tourId:z65.string(),version:z65.string(),status:z65.string(),completedAt:z65.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z65.array(UserTourDTOSchema))}});import{z as z66}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=z66.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z66.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z66.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z66.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z66.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z66.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z66.enum(["user","agent","system"]),SupportReportTagSchema=z66.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z66.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z66.object({organization:z66.object({id:z66.string().trim().min(1).max(255),name:z66.string().trim().max(240).optional()}),project:z66.object({id:z66.uuid(),name:z66.string().trim().max(240).optional(),createdAt:z66.coerce.date().optional()}).optional(),environment:z66.string().trim().max(255).optional(),clientVersion:z66.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z66.object({message:z66.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z66.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z66.string().trim().max(200).optional(),limit:z66.coerce.number().int().min(1).max(100).default(50),offset:z66.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z66.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z66.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z66.uuid().nullable().optional(),note:z66.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=z66.object({message:z66.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z66.object({kind:SupportReportLinkKindSchema,label:z66.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z66.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z66.object({kind:SupportReportActorKindSchema,id:z66.string().nullable(),name:z66.string().nullable()}),SupportReportLinkDTOSchema=z66.object({id:z66.uuid(),kind:SupportReportLinkKindSchema,label:z66.string(),url:SupportReportHttpUrlSchema,externalId:z66.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z66.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z66.object({id:z66.uuid(),kind:SupportReportEventKindSchema,body:z66.string().nullable(),metadata:z66.record(z66.string(),z66.unknown()),actor:SupportReportActorDTOSchema,createdAt:z66.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z66.object({id:z66.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z66.array(z66.string()),source:SupportReportSourceSchema,message:z66.string(),reporter:z66.object({id:z66.string().nullable(),name:z66.string().nullable(),email:z66.string().nullable()}),organization:z66.object({id:z66.string().nullable(),name:z66.string()}),project:z66.object({id:z66.uuid().nullable(),name:z66.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z66.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z66.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z66.string().nullable(),deliveredAt:z66.coerce.date().nullable()}).nullable(),duplicateOfReportId:z66.uuid().nullable(),resolvedAt:z66.coerce.date().nullable(),createdAt:z66.coerce.date(),updatedAt:z66.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z66.string().nullable(),clientVersion:z66.string().nullable(),links:z66.array(SupportReportLinkDTOSchema),events:z66.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z66.object({reports:z66.array(SupportReportSummaryDTOSchema),total:z66.number().int().nonnegative(),statusCounts:z66.object({new:z66.number().int().nonnegative(),in_progress:z66.number().int().nonnegative(),waiting:z66.number().int().nonnegative(),resolved:z66.number().int().nonnegative(),duplicate:z66.number().int().nonnegative(),irrelevant:z66.number().int().nonnegative(),ignored:z66.number().int().nonnegative()}),limit:z66.number().int().positive(),offset:z66.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z66.object({id:z66.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z66.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z67}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=z67.iso.datetime({offset:!0}).pipe(z67.coerce.date()),OpsRecentChatInputSchema=z67.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z67.string().trim().min(1).max(255).optional(),limit:z67.coerce.number().int().min(1).max(200).default(100),cursor:z67.string().trim().min(1).max(2e3).optional(),slim:z67.boolean().default(!0),reason:z67.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=z67.object({id:z67.string(),threadId:z67.string(),providerMessageId:z67.string().nullable(),invocationId:z67.string().nullable(),env:z67.string().nullable(),role:z67.string(),parts:z67.array(z67.record(z67.string(),z67.unknown())),metadata:z67.object({status:z67.string().optional(),traceUrl:z67.string().optional(),externalFileChanges:z67.array(z67.unknown()).optional()}),stats:z67.object({toolCount:z67.number().int().nonnegative(),failedToolCount:z67.number().int().nonnegative()}),createdAt:z67.iso.datetime({offset:!0}),project:z67.object({id:z67.string(),name:z67.string(),displayName:z67.string().nullable(),organizationId:z67.string().nullable()})}),OpsRecentChatResponseSchema=z67.object({target:z67.object({backendProfile:OpsBackendProfileSchema,projectEnv:z67.string().nullable()}),window:z67.object({from:z67.iso.datetime({offset:!0}),to:z67.iso.datetime({offset:!0})}),messages:z67.object({items:z67.array(OpsRecentChatMessageSchema),nextCursor:z67.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z68}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=z68.object({backendProfile:OpsBackendProfileSchema,provider:z68.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z68.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z68.object({backendProfile:OpsBackendProfileSchema,provider:z68.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z68.literal(!1),reason:z68.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z69}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=z69.object({packageManager:z69.string().trim().min(1).max(200).nullable(),trackedLockfiles:z69.array(z69.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z69.string().trim().min(1)}),OpsProjectPackageManagerSchema=z69.object({target:z69.object({backendProfile:OpsBackendProfileSchema,projectId:z69.uuid(),projectEnv:z69.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z70}from"zod";function createAgentRunWebhookEventDataSchema(status){return z70.object({run:z70.object({id:z70.string(),agentName:z70.string(),trigger:z70.string(),status:z70.literal(status),startedAt:z70.string().nullable(),finishedAt:z70.string().nullable(),reason:z70.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=z70.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z70.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z70.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z70.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z70.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z70.union([z70.literal(0),z70.literal(5),z70.literal(30),z70.literal(60)]),EntryChangedWebhookEventDataSchema=z70.object({reason:WebhookEntryChangeReasonSchema,operationId:z70.string().optional(),batch:z70.object({index:z70.number().int().positive(),total:z70.number().int().positive()}).optional(),changes:z70.array(z70.object({action:WebhookEntryChangeActionSchema,contentType:z70.string(),id:z70.string(),documentId:z70.string(),locale:z70.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z70.object({form:z70.object({id:z70.string(),label:z70.string()}),submission:z70.object({id:z70.string(),data:z70.record(z70.string(),z70.unknown()),submittedAt:z70.string()})}),PublishStartedWebhookEventDataSchema=z70.object({publication:z70.object({status:z70.literal("publishing"),startedAt:z70.string()})}),PublishSucceededWebhookEventDataSchema=z70.object({publication:z70.object({status:z70.literal("published"),url:z70.string(),publishedAt:z70.string(),firstPublish:z70.boolean()})}),PublishFailedWebhookEventDataSchema=z70.object({publication:z70.object({status:z70.literal("failed"),reason:z70.string()})}),PublishUnpublishedWebhookEventDataSchema=z70.object({publication:z70.object({previousUrl:z70.string(),unpublishedAt:z70.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z70.object({review:z70.object({id:z70.string(),runId:z70.string(),agentName:z70.string(),classification:z70.string(),summary:z70.string(),reasons:z70.array(z70.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z70.object({review:z70.object({id:z70.string(),runId:z70.string(),agentName:z70.string(),resolution:z70.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z70.object({report:z70.object({weekStart:z70.string(),weekEnd:z70.string(),pageviews:z70.number(),visitors:z70.number(),previousPageviews:z70.number(),previousVisitors:z70.number()})}),MediaAssetWebhookEventDataSchema=z70.object({id:z70.string().nullable(),name:z70.string().nullable(),type:z70.string(),mimeType:z70.string().nullable(),fileSize:z70.number().nullable()}),MediaUploadedWebhookEventDataSchema=z70.object({asset:MediaAssetWebhookEventDataSchema,operation:z70.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z70.object({asset:MediaAssetWebhookEventDataSchema,operation:z70.enum(["updated","moved","analysis"]),analysis:z70.object({category:z70.string(),status:z70.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z70.object({asset:MediaAssetWebhookEventDataSchema,operation:z70.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z70.object({asset:MediaAssetWebhookEventDataSchema,operation:z70.literal("generated"),generation:z70.object({model:z70.string(),mode:z70.string()})}),MediaProcessingFailedWebhookEventDataSchema=z70.object({asset:MediaAssetWebhookEventDataSchema,operation:z70.enum(["analysis","generation"]),failure:z70.object({code:z70.string()})}),DomainCreatedWebhookEventDataSchema=z70.object({domain:z70.object({id:z70.string(),hostname:z70.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z70.object({domain:z70.object({id:z70.string(),hostname:z70.string()})}),LabelChangedWebhookEventDataSchema=z70.object({changes:z70.array(z70.object({action:z70.enum(["created","updated","deleted"]),key:z70.string(),locale:z70.string(),value:z70.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z70.object({locale:z70.object({code:z70.string(),isDefault:z70.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z70.object({locale:z70.object({code:z70.string(),previousCode:z70.string()})}),LocaleDeletedWebhookEventDataSchema=z70.object({locale:z70.object({code:z70.string(),entriesDeleted:z70.number().int().nonnegative(),labelsDeleted:z70.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z70.object({environment:z70.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z70.object({environment:z70.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z70.object({merge:z70.object({id:z70.string(),from:BranchSchema,to:BranchSchema,applied:z70.array(z70.object({surface:SurfaceNameSchema,count:z70.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z70.object({environment:z70.object({name:BranchSchema}),version:z70.object({versionId:z70.uuid(),name:z70.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=z70.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z70.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z70.discriminatedUnion("source",[z70.object({source:z70.literal("literal"),value:z70.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z70.object({source:z70.literal("secret"),key:z70.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z70.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z70.object({name:z70.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z70.object({name:z70.string(),source:z70.enum(["literal","secret"]),secretKey:z70.string().nullable(),secretPrefix:z70.string().nullable(),configured:z70.literal(!0)}),WebhookFilterSchema=z70.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z70.string().min(1).max(255).optional(),agentName:z70.string().min(1).max(120).optional(),mediaType:z70.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z70.string().min(1).max(255).optional(),locale:z70.string().min(1).max(120).optional()}),JsonValueSchema=z70.lazy(()=>z70.union([z70.string(),z70.number(),z70.boolean(),z70.null(),z70.array(JsonValueSchema),z70.record(z70.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z70.object({name:z70.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z70.url(),enabled:z70.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z70.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z70.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z70.object({name:z70.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z70.url().optional(),enabled:z70.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z70.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z70.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z70.object({eventType:WebhookEventTypeSchema.optional(),data:z70.record(z70.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z70.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z70.uuid(),name:z70.string(),eventType:WebhookEventTypeSchema,enabled:z70.boolean(),destination:z70.object({host:z70.string(),maskedUrl:z70.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z70.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z70.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z70.coerce.date().nullable(),deliveryStats24h:z70.object({succeeded:z70.number().int().nonnegative(),failed:z70.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z70.uuid(),projectId:z70.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z70.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z70.number().int().positive(),test:z70.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z70.number().int().nonnegative(),responseStatus:z70.number().int().nullable(),lastErrorCode:z70.string().nullable(),lastErrorMessage:z70.string().nullable(),payloadAvailable:z70.boolean(),destination:z70.object({host:z70.string(),maskedUrl:z70.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z70.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z70.string().nullable(),qstashMessageId:z70.string().nullable(),deliveredAt:z70.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z70.object({items:z70.array(WebhookDeliveryDTOSchema),pagination:z70.object({page:z70.number().int().positive(),limit:z70.number().int().positive(),total:z70.number().int().nonnegative(),totalPages:z70.number().int().positive(),hasMore:z70.boolean()}),stats:z70.object({total:z70.number().int().nonnegative(),succeeded:z70.number().int().nonnegative(),failed:z70.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z70.object({id:z70.uuid(),deliveryId:z70.uuid(),attempt:z70.number().int().positive(),status:z70.enum(["delivering","succeeded","failed"]),responseStatus:z70.number().int().nullable(),durationMs:z70.number().int().nonnegative(),responseExcerpt:z70.string().nullable(),errorCode:z70.string().nullable(),errorMessage:z70.string().nullable(),createdAt:z70.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z70.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z70.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z71}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=z71.object({key:z71.literal("fimo-2"),enabled:z71.boolean(),dismissed:z71.boolean().default(!1),interacted:z71.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z72}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=z72.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z72.object({total:z72.number(),base:z72.number(),purchases:z72.number(),awards:z72.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z72.object({id:z72.string(),name:z72.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z72.object({type:z72.string(),brand:z72.string().nullable(),last4:z72.string().nullable(),expirationDate:z72.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z72.object({currency:z72.string(),nextPaymentAmount:z72.number().nullable(),nextPaymentAt:z72.string().nullable(),billingInterval:z72.string().nullable(),totalAmount:z72.number().nullable(),discountAmount:z72.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z72.object({id:z72.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z72.string().nullable(),currentPeriodEndsAt:z72.string().nullable(),renewsAt:z72.string().nullable(),cancelAt:z72.string().nullable(),renewAutomatically:z72.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z72.object({type:z72.enum(["low_balance","critical_balance","approaching_limit"]),message:z72.string(),estimatedPromptsRemaining:z72.number().nullable(),avgCostPerPrompt:z72.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z72.object({monthlyCredits:z72.number().nullable(),usedThisPeriod:z72.number(),remainingThisPeriod:z72.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z72.object({organizationId:z72.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z72.string().nullable(),tenureDays:z72.number().int().nonnegative(),capturedAt:z72.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z72.object({hasSubscription:z72.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z72.number().nullable(),alerts:z72.array(CreditAlertDTOSchema),portalUrl:z72.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z72.object({creditCount:z72.number().int().positive(),expiresAt:z72.string().datetime().nullable().optional(),message:z72.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z72.literal("free"),amountCents:z72.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z72.literal("purchase"),amountCents:z72.number().int().positive()}),CreditTopupRequestDTOSchema=z72.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z72.object({success:z72.boolean(),transactionId:z72.string().nullable(),newBalance:z72.number(),creditCount:z72.number(),type:z72.enum(["free","purchase"]),invoiceId:z72.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z73}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=z73.object({totalCredits:z73.number(),totalCostUsd:z73.number(),totalMessages:z73.number(),avgCostPerMessage:z73.number(),periodStart:z73.string().nullable(),periodEnd:z73.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z73.object({projectId:z73.string(),projectName:z73.string(),projectDisplayName:z73.string().nullable(),credits:z73.number(),costUsd:z73.number(),messages:z73.number(),percentage:z73.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z73.object({userId:z73.string(),userName:z73.string().nullable(),userEmail:z73.string().email().nullable(),credits:z73.number(),costUsd:z73.number(),messages:z73.number(),percentage:z73.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z73.object({date:z73.string(),credits:z73.number(),costUsd:z73.number(),messages:z73.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z73.object({userId:z73.string(),userName:z73.string().nullable(),userEmail:z73.string().email().nullable(),credits:z73.number(),costUsd:z73.number(),messages:z73.number(),percentage:z73.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z73.object({projectId:z73.string(),projectName:z73.string(),projectDisplayName:z73.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z73.array(UsageByUserForProjectDTOSchema),timeline:z73.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z73.object({summary:UsageSummaryDTOSchema,byProject:z73.array(UsageByProjectDTOSchema),byUser:z73.array(UsageByUserDTOSchema),timeline:z73.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z74}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=z74.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z74.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z74.object({startDate:z74.string().optional(),endDate:z74.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z74.coerce.number().int().positive().default(1),limit:z74.coerce.number().int().positive().max(100).default(20),sortBy:z74.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z74.string().optional(),activeOnly:z74.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z74.object({totalCredits:z74.number(),totalCostUsd:z74.number(),totalMessages:z74.number(),avgCostPerMessage:z74.number(),avgCreditsPerMessage:z74.number(),periodStart:z74.string(),periodEnd:z74.string(),creditsChange:z74.number().nullable(),costChange:z74.number().nullable(),messagesChange:z74.number().nullable(),unattributedCredits:z74.number(),unattributedCostUsd:z74.number(),unattributedMessages:z74.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z74.object({date:z74.string(),credits:z74.number(),costUsd:z74.number(),messages:z74.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z74.object({organizationId:z74.string(),organizationName:z74.string(),credits:z74.number(),costUsd:z74.number(),messages:z74.number(),percentage:z74.number(),userCount:z74.number(),projectCount:z74.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z74.object({userId:z74.string(),userName:z74.string().nullable(),userEmail:z74.string().nullable(),userImage:z74.string().nullable(),organizationId:z74.string().nullable(),organizationName:z74.string().nullable(),credits:z74.number(),costUsd:z74.number(),messages:z74.number(),percentage:z74.number(),projectCount:z74.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z74.object({projectId:z74.string(),projectName:z74.string(),projectDisplayName:z74.string().nullable(),organizationId:z74.string(),organizationName:z74.string(),credits:z74.number(),costUsd:z74.number(),messages:z74.number(),percentage:z74.number(),userCount:z74.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z74.object({id:z74.string(),name:z74.string(),value:z74.number(),percentage:z74.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z74.object({day:z74.number(),hour:z74.number(),value:z74.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z74.object({summary:UsageOverviewSummaryDTOSchema,timeline:z74.array(UsageTimelinePointDTOSchema),topOrganizations:z74.array(OrganizationUsageRowDTOSchema),topUsers:z74.array(UserUsageRowDTOSchema),topProjects:z74.array(ProjectUsageRowDTOSchema),creditDistribution:z74.array(UsageDistributionItemDTOSchema),userDistribution:z74.array(UsageDistributionItemDTOSchema),heatmap:z74.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z74.object({page:z74.number(),limit:z74.number(),totalItems:z74.number(),totalPages:z74.number(),hasMore:z74.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z74.object({organizations:z74.array(OrganizationUsageRowDTOSchema),top:z74.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z74.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z74.object({users:z74.array(ExtendedUserUsageRowDTOSchema),top:z74.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z74.string(),ownerName:z74.string().nullable(),ownerEmail:z74.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z74.object({projects:z74.array(ExtendedProjectUsageRowDTOSchema),top:z74.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z74.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z74.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z74.object({credits:z74.number(),costUsd:z74.number(),messages:z74.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z74.object({id:z74.string(),name:z74.string(),createdAt:z74.string(),memberCount:z74.number(),projectCount:z74.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z74.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z74.object({id:z74.string(),name:z74.string().nullable(),email:z74.string(),image:z74.string().nullable(),createdAt:z74.string(),organizationCount:z74.number(),projectCount:z74.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z74.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z74.object({id:z74.string(),name:z74.string(),displayName:z74.string().nullable(),createdAt:z74.string(),organizationId:z74.string(),organizationName:z74.string(),ownerId:z74.string(),ownerName:z74.string().nullable(),ownerEmail:z74.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z74.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z75}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=z75.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z75.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z75.object({command:z75.string().min(1).max(1e4),cwd:z75.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z75.record(z75.string(),z75.string()).optional(),name:z75.string().optional(),waitForCompletion:z75.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z75.object({identifier:z75.string(),status:SandboxProcessStatusSchema,command:z75.string().optional(),startedAt:z75.string().optional(),exitCode:z75.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z75.object({processes:z75.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z75.object({processId:z75.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z75.object({success:z75.boolean(),message:z75.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z76}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_agent_report();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_control_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_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_project_migration_dto();init_analytics_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&¶ms.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:path53,message}=issue;return`${Array.isArray(path53)&&path53.length>0?`${path53.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,branch,base)===normalized?base:void 0}catch{return}}function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}var SandboxReadinessError,ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_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,path53,status,detail,code2,body){super(`API ${method} ${path53} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path53,this.status=status,this.detail=detail,this.code=code2,this.body=body}};__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_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}branch;withBranch(branch){let next2=new _FimoApiClient(this.cfg);return next2.branch=branch,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(path53,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.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...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",path53,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path53,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.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch),fimoFetch(`${this.cfg.apiUrl}${path53}`,{...init,headers})}async rawRequest(path53,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,this.branch);let response=await fimoFetch(`${this.cfg.apiUrl}${path53}`,{...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"} ${path53} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: tenant-scoped call requires a Branch. Use `client.withBranch(branch)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}projectBranchManagementPath(projectId,route){if(!this.branch)throw new Error("FimoApiClient: Branch-scoped management call requires a Branch. Use `client.withBranch(branch)` before calling Branch CRUD methods.");return`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(this.branch)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,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&¶ms.set("limit",String(query.limit)),query.before&¶ms.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&¶ms.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 trackProjectEvent(projectId,event,properties={}){await this.request(`/api/management/projects/${projectId}/track`,{method:"POST",body:JSON.stringify({event,properties})})}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectBranchManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectBranchManagementPath(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&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,options={}){let query=`?page=${options.page??1}&limit=${options.limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data}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 listBranches(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentBranches&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/branches${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listBranches(projectId,{includeAgentBranches:!0}),current=branches.find(candidate=>branchNameOf(candidate)===branch),visited=new Set;for(;current&&!visited.has(branchNameOf(current));){if(visited.add(branchNameOf(current)),current.resolvedEnvironment)return current.resolvedEnvironment.id;let parent2=parentBranchOf(current);current=parent2?branches.find(candidate=>branchNameOf(candidate)===parent2):void 0}return PREVIEW_ENVIRONMENT_KEY}async getBranch(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`)).data}async createBranch(projectId,input){return(await this.request(`/api/management/projects/${projectId}/branches`,{method:"POST",body:JSON.stringify(input)})).data}async syncBranch(projectId,branch,input={}){let body=await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/sync`,{method:"POST",body:JSON.stringify(input)});return{branch:body.data.branch??body.data.env,conflicts:body.data.conflicts}}async deleteBranch(projectId,branch){await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}`,{method:"DELETE"})}async getBranchDiff(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff${qs?`?${qs}`:""}`)).data}async getBranchStatus(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,branch,path53,opts={}){let qs=lazyFetchQs(opts.against,{path:path53});return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,branch,fromBranch,filePath){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,branch,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getSchemaTypeDiff(projectId,branch,typeName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getAssetDiff(projectId,branch,assetId,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getTranslationRowDiff(projectId,branch,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async getFormSchemaDiff(projectId,branch,formName,opts={}){let qs=lazyFetchQs(opts.against),path53=`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path53}?${qs}`:path53)).data}async mergeBranch(projectId,branch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,branch,mergeId){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/conflicts`)).data}async putResolveDraft(projectId,branch,fromBranch,body){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,branch,fromBranch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/merge/${encodeURIComponent(fromBranch)}/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,branch,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.branch&¶ms.set("env",opts.branch),opts.status&¶ms.set("status",opts.status),opts.page!==void 0&¶ms.set("page",String(opts.page)),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)}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,branch){let remote=(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,branch);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectBranchManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectBranchManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).data}async getGitCredential(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,branch){return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox`)).data}async getSandboxLogs(projectId,branch,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.before&¶ms.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&¶ms.set("noRestart","true"),options.wait!==void 0&¶ms.set("wait",String(options.wait));let search=params.toString(),query=search?`?${search}`:"",response=await this.rawRequest(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/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(`
|
|
61
61
|
|
|
62
62
|
`);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
|
|
63
63
|
|
|
64
64
|
`);let eventName="message",dataLines=[];for(let line of rawEvent.split(`
|
|
65
65
|
`))line.startsWith("event:")?eventName=line.slice(6).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).trim());if(dataLines.length===0)continue;let payload=dataLines.join(`
|
|
66
66
|
`);if(eventName==="progress")try{let parsed=JSON.parse(payload);onProgress?.(parsed)}catch{}else if(eventName==="complete"){completed=!0;try{let complete=JSON.parse(payload);readiness=complete.readiness??null,timings=complete.timings??null}catch{}}else if(eventName==="error")try{let parsed=JSON.parse(payload);errorMessage6=parsed.message??"Sandbox pull failed",errorCode=parsed.code}catch{errorMessage6="Sandbox pull failed"}}}}finally{reader.releaseLock()}if(errorMessage6)throw errorCode==="readiness_failed"?new SandboxReadinessError(errorMessage6):new Error(errorMessage6);if(!completed)throw new Error("Sandbox pull stream ended before completion");return{readiness:readiness??{status:"skipped",reason:"not_reported",durationMs:0},timings:timings??{dependencyInstallMs:0,serverStartMs:0,readinessMs:readiness?.durationMs??0,totalSandboxMs:0}}}async checkSubdomain(projectId,slug){return(await this.request(`/api/management/projects/${projectId}/subdomain/check?slug=${encodeURIComponent(slug)}`)).data}async renameSubdomain(projectId,slug){return(await this.request(`/api/management/projects/${projectId}/subdomain`,{method:"PATCH",body:JSON.stringify({slug})})).data}async suggestSubdomains(projectId,opts){let params=new URLSearchParams;opts?.base&¶ms.set("base",opts.base),opts?.max!==void 0&¶ms.set("max",String(opts.max));let query=params.toString();return(await this.request(`/api/management/projects/${projectId}/subdomain/suggestions${query?`?${query}`:""}`)).data.suggestions}async listProjectDomains(projectId){return(await this.request(`/api/management/projects/${projectId}/domains`,{},{allow403:!0})).data}async addProjectDomain(projectId,input){return(await this.request(`/api/management/projects/${projectId}/domains`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async refreshProjectDomain(projectId,domainId){return(await this.request(`/api/management/projects/${projectId}/domains/${domainId}/refresh`,{method:"POST"},{allow403:!0})).data}async removeProjectDomain(projectId,domainId){await this.request(`/api/management/projects/${projectId}/domains/${domainId}`,{method:"DELETE"},{allow403:!0})}async searchRegisteredDomains(input){return(await this.request("/api/domains/search",{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async getRegisteredDomainPricing(domain){return(await this.request(`/api/domains/pricing/${encodeURIComponent(domain)}`,{},{allow403:!0})).data}async listOwnedRegisteredDomains(organizationId){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}`,{},{allow403:!0})).data}async purchaseRegisteredDomain(organizationId,input){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}/purchase`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async refreshRegisteredDomainPayment(organizationId,domainId){return(await this.request(`/api/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,{method:"POST"},{allow403:!0})).data}async listSchemas(projectId){return this.request(this.tenantPath(projectId,"/schema"))}async getSchema(projectId,typeName){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`))).data}async createSchema(projectId,contentType){return(await this.request(this.tenantPath(projectId,"/schema/types"),{method:"POST",body:JSON.stringify({contentType})})).data}async updateSchema(projectId,typeName,contentType,operations=[]){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`),{method:"PUT",body:JSON.stringify({contentType,...operations.length>0?{operations}:{}})})).data}async upsertSchemas(projectId,contentTypes,operations=[]){return(await this.request(this.tenantPath(projectId,"/schema/batch"),{method:"POST",body:JSON.stringify({contentTypes,...operations.length>0?{operations}:{}})})).data}async deleteSchema(projectId,typeName){return(await this.request(this.tenantPath(projectId,`/schema/types/${typeName}`),{method:"DELETE"})).data}async listEntries(projectId,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return this.request(this.tenantPath(projectId,`/entries/${typeName}${query}`))}async getEntry(projectId,typeName,id,locale){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`))).data}async createEntry(projectId,typeName,data2){return(await this.request(this.tenantPath(projectId,`/entries/${typeName}`),{method:"POST",body:JSON.stringify(data2)})).data}async updateEntry(projectId,typeName,id,locale,data2){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`),{method:"PUT",body:JSON.stringify(data2)})).data}async deleteEntry(projectId,typeName,id,locale){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/entries/${typeName}/${id}${query}`),{method:"DELETE"})).data}async queryEntries(projectId,sql){return this.request(this.tenantPath(projectId,"/entries/query"),{method:"POST",body:JSON.stringify({sql})})}async bulkCreateEntries(projectId,typeName,entries2){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-create`),{method:"POST",body:JSON.stringify({entries:entries2})})}async bulkUpdateEntries(projectId,typeName,payload){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-update`),{method:"POST",body:JSON.stringify(payload)})}async bulkDeleteEntries(projectId,typeName,payload){return this.request(this.tenantPath(projectId,`/entries/${typeName}/bulk-delete`),{method:"POST",body:JSON.stringify(payload)})}async getSingle(projectId,typeName,params){let searchParams=new URLSearchParams;params?.locale&&searchParams.set("locale",params.locale),params?.populate&&searchParams.set("populate",params.populate);let query=searchParams.size>0?`?${searchParams.toString()}`:"";return(await this.request(this.tenantPath(projectId,`/documents/${typeName}${query}`))).data}async updateSingle(projectId,typeName,locale,data2){let query=locale?`?${new URLSearchParams({locale}).toString()}`:"";return(await this.request(this.tenantPath(projectId,`/documents/${typeName}${query}`),{method:"PUT",body:JSON.stringify(data2)})).data}async listAssets(projectId,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return this.request(this.tenantPath(projectId,`/assets${query}`))}async getAsset(projectId,id){return this.request(this.tenantPath(projectId,`/assets/${id}`))}async readAsset(projectId,id,request){return(await this.request(this.tenantPath(projectId,`/assets/${id}/read`),{method:"POST",body:JSON.stringify(request)})).data}async uploadAsset(projectId,formData){return(await(await this.rawRequest(this.tenantPath(projectId,"/assets/upload"),{method:"POST",body:formData})).json()).data}async generate(projectId,payload){return(await this.request(this.tenantPath(projectId,"/assets/generate"),{method:"POST",body:JSON.stringify(payload)})).data}async createFolder(projectId,name,parentId){return(await this.request(this.tenantPath(projectId,"/assets/folders"),{method:"POST",body:JSON.stringify({name,parentId:parentId??null})})).data}async moveAsset(projectId,id,parentId){return(await this.request(this.tenantPath(projectId,`/assets/${id}/move`),{method:"POST",body:JSON.stringify({parentId})})).data}async getAssetReferenceImpact(projectId,request){return(await(await this.rawRequest(this.tenantPath(projectId,"/assets/reference-impact"),{method:"POST",headers:{Accept:"application/x-ndjson","Content-Type":"application/json"},body:JSON.stringify(request)})).text()).split(`
|
|
67
|
-
`).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))}async previewAssetReferenceReplacement(projectId,sourceAssetId,replacementAssetId){return(await this.request(this.tenantPath(projectId,`/assets/${sourceAssetId}/replacement-preview`),{method:"POST",body:JSON.stringify({replacementAssetId})})).data}async replaceAssetReferences(projectId,sourceAssetId,replacementAssetId){return(await this.request(this.tenantPath(projectId,`/assets/${sourceAssetId}/replace-references`),{method:"POST",body:JSON.stringify({replacementAssetId})})).data}async deleteAsset(projectId,id){return(await this.request(this.tenantPath(projectId,`/assets/${id}`),{method:"DELETE"})).data}async destroyAsset(projectId,id){return(await this.request(this.tenantPath(projectId,`/assets/${id}/permanent`),{method:"DELETE"})).data}async destroyAssetWithReplacement(projectId,id,replacementAssetId){return(await this.request(this.tenantPath(projectId,`/assets/${id}/replace-and-destroy`),{method:"POST",body:JSON.stringify({replacementAssetId})})).data}async listForms(projectId){return(await this.request(this.tenantPath(projectId,"/forms"))).data}async getForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`))).data}async createForm(projectId,data2){return(await this.request(this.tenantPath(projectId,"/forms"),{method:"POST",body:JSON.stringify(data2)})).data}async updateForm(projectId,id,data2){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data2)})).data}async deleteForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"DELETE"})).data}async listLabels(projectId,locale){let query=locale?`?locale=${encodeURIComponent(locale)}`:"";return(await this.request(this.tenantPath(projectId,`/labels${query}`))).data}async setLabel(projectId,data2){return(await this.request(this.tenantPath(projectId,"/labels"),{method:"POST",body:JSON.stringify(data2)})).data}async setLabels(projectId,records){return(await this.request(this.tenantPath(projectId,"/labels/sync"),{method:"POST",body:JSON.stringify({created:records,updated:[],deleted:[]})})).data}async deleteLabel(projectId,locale,key){return(await this.request(this.tenantPath(projectId,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{method:"DELETE"})).data}async getProjectAnalytics(projectId,params){let search=new URLSearchParams;params?.preset&&search.set("preset",params.preset),params?.groupBy&&search.set("groupBy",params.groupBy),params?.from&&search.set("from",params.from),params?.to&&search.set("to",params.to),params?.days!==void 0&&search.set("days",String(params.days));let query=search.toString();return(await this.request(this.projectBranchManagementPath(projectId,`/analytics${query?`?${query}`:""}`))).data}async setAnalyticsAnnotation(projectId,date,content2){return(await this.request(this.projectBranchManagementPath(projectId,`/analytics/annotations/${date}`),{method:"PUT",body:JSON.stringify({content:content2})}))?.data??null}async deleteAnalyticsAnnotation(projectId,date){return await this.setAnalyticsAnnotation(projectId,date,""),null}async listFormSubmissions(projectId,formId,params){let search=new URLSearchParams;params?.limit!==void 0&&search.set("limit",String(params.limit)),params?.offset!==void 0&&search.set("offset",String(params.offset)),params?.searchQuery&&search.set("searchQuery",params.searchQuery),params?.sortDirection&&search.set("sortDirection",params.sortDirection);let query=search.toString();return await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions${query?`?${query}`:""}`))}async getFormSubmission(projectId,formId,submissionId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/${submissionId}`))).data}async getFormSubmissionStats(projectId,formId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/stats`))).data}}}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports2){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,"isAlias"),isDocument2=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,"isDocument"),isMap=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,"isMap"),isPair=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,"isPair"),isScalar=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,"isScalar"),isSeq=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ,"isSeq");function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}__name(isCollection,"isCollection");function isNode2(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}__name(isNode2,"isNode");var hasAnchor=__name(node=>(isScalar(node)||isCollection(node))&&!!node.anchor,"hasAnchor");exports2.ALIAS=ALIAS;exports2.DOC=DOC;exports2.MAP=MAP;exports2.NODE_TYPE=NODE_TYPE;exports2.PAIR=PAIR;exports2.SCALAR=SCALAR;exports2.SEQ=SEQ;exports2.hasAnchor=hasAnchor;exports2.isAlias=isAlias;exports2.isCollection=isCollection;exports2.isDocument=isDocument2;exports2.isMap=isMap;exports2.isNode=isNode2;exports2.isPair=isPair;exports2.isScalar=isScalar;exports2.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(exports2){"use strict";var identity2=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit2(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}__name(visit2,"visit");visit2.BREAK=BREAK;visit2.SKIP=SKIP;visit2.REMOVE=REMOVE;function visit_(key,node,visitor,path53){let ctrl=callVisitor(key,node,visitor,path53);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path53,ctrl),visit_(key,ctrl,visitor,path53);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path53=Object.freeze(path53.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path53);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path53=Object.freeze(path53.concat(node));let ck=visit_("key",node.key,visitor,path53);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path53);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visit_,"visit_");async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}__name(visitAsync,"visitAsync");visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path53){let ctrl=await callVisitor(key,node,visitor,path53);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path53,ctrl),visitAsync_(key,ctrl,visitor,path53);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path53=Object.freeze(path53.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path53);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path53=Object.freeze(path53.concat(node));let ck=await visitAsync_("key",node.key,visitor,path53);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path53);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visitAsync_,"visitAsync_");function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}__name(initVisitor,"initVisitor");function callVisitor(key,node,visitor,path53){if(typeof visitor=="function")return visitor(key,node,path53);if(identity2.isMap(node))return visitor.Map?.(key,node,path53);if(identity2.isSeq(node))return visitor.Seq?.(key,node,path53);if(identity2.isPair(node))return visitor.Pair?.(key,node,path53);if(identity2.isScalar(node))return visitor.Scalar?.(key,node,path53);if(identity2.isAlias(node))return visitor.Alias?.(key,node,path53)}__name(callVisitor,"callVisitor");function replaceNode(key,path53,node){let parent2=path53[path53.length-1];if(identity2.isCollection(parent2))parent2.items[key]=node;else if(identity2.isPair(parent2))key==="key"?parent2.key=node:parent2.value=node;else if(identity2.isDocument(parent2))parent2.contents=node;else{let pt2=identity2.isAlias(parent2)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}__name(replaceNode,"replaceNode");exports2.visit=visit2;exports2.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=__name(tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),"escapeTagName"),Directives=class _Directives{static{__name(this,"Directives")}constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity2.isNode(doc.contents)){let tags={};visit2.visit(doc.contents,(_key,node)=>{identity2.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
67
|
+
`).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))}async replaceAssetReferences(projectId,sourceAssetId,replacementAssetId){return(await this.request(this.tenantPath(projectId,`/assets/${sourceAssetId}/replace-references`),{method:"POST",body:JSON.stringify({replacementAssetId})})).data}async replaceAndRemoveAsset(projectId,sourceAssetId,replacementAssetId){return(await this.request(this.tenantPath(projectId,"/assets/removals"),{method:"POST",body:JSON.stringify({intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId})})).data}async deleteAsset(projectId,id){return(await this.request(this.tenantPath(projectId,`/assets/${id}`),{method:"DELETE"})).data}async destroyAsset(projectId,id){return(await this.request(this.tenantPath(projectId,`/assets/${id}/permanent`),{method:"DELETE"})).data}async destroyAssetWithReplacement(projectId,id,replacementAssetId){return(await this.request(this.tenantPath(projectId,`/assets/${id}/replace-and-destroy`),{method:"POST",body:JSON.stringify({replacementAssetId})})).data}async listForms(projectId){return(await this.request(this.tenantPath(projectId,"/forms"))).data}async getForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`))).data}async createForm(projectId,data2){return(await this.request(this.tenantPath(projectId,"/forms"),{method:"POST",body:JSON.stringify(data2)})).data}async updateForm(projectId,id,data2){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data2)})).data}async deleteForm(projectId,id){return(await this.request(this.tenantPath(projectId,`/forms/${id}`),{method:"DELETE"})).data}async listLabels(projectId,locale){let query=locale?`?locale=${encodeURIComponent(locale)}`:"";return(await this.request(this.tenantPath(projectId,`/labels${query}`))).data}async setLabel(projectId,data2){return(await this.request(this.tenantPath(projectId,"/labels"),{method:"POST",body:JSON.stringify(data2)})).data}async setLabels(projectId,records){return(await this.request(this.tenantPath(projectId,"/labels/sync"),{method:"POST",body:JSON.stringify({created:records,updated:[],deleted:[]})})).data}async deleteLabel(projectId,locale,key){return(await this.request(this.tenantPath(projectId,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{method:"DELETE"})).data}async getProjectAnalytics(projectId,params){let search=new URLSearchParams;params?.preset&&search.set("preset",params.preset),params?.groupBy&&search.set("groupBy",params.groupBy),params?.from&&search.set("from",params.from),params?.to&&search.set("to",params.to),params?.days!==void 0&&search.set("days",String(params.days));let query=search.toString();return(await this.request(this.projectBranchManagementPath(projectId,`/analytics${query?`?${query}`:""}`))).data}async setAnalyticsAnnotation(projectId,date,content2){return(await this.request(this.projectBranchManagementPath(projectId,`/analytics/annotations/${date}`),{method:"PUT",body:JSON.stringify({content:content2})}))?.data??null}async deleteAnalyticsAnnotation(projectId,date){return await this.setAnalyticsAnnotation(projectId,date,""),null}async listFormSubmissions(projectId,formId,params){let search=new URLSearchParams;params?.limit!==void 0&&search.set("limit",String(params.limit)),params?.offset!==void 0&&search.set("offset",String(params.offset)),params?.searchQuery&&search.set("searchQuery",params.searchQuery),params?.sortDirection&&search.set("sortDirection",params.sortDirection);let query=search.toString();return await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions${query?`?${query}`:""}`))}async getFormSubmission(projectId,formId,submissionId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/${submissionId}`))).data}async getFormSubmissionStats(projectId,formId){return(await this.request(this.tenantPath(projectId,`/forms/${formId}/submissions/stats`))).data}}}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports2){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,"isAlias"),isDocument2=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,"isDocument"),isMap=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,"isMap"),isPair=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,"isPair"),isScalar=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,"isScalar"),isSeq=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ,"isSeq");function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}__name(isCollection,"isCollection");function isNode2(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}__name(isNode2,"isNode");var hasAnchor=__name(node=>(isScalar(node)||isCollection(node))&&!!node.anchor,"hasAnchor");exports2.ALIAS=ALIAS;exports2.DOC=DOC;exports2.MAP=MAP;exports2.NODE_TYPE=NODE_TYPE;exports2.PAIR=PAIR;exports2.SCALAR=SCALAR;exports2.SEQ=SEQ;exports2.hasAnchor=hasAnchor;exports2.isAlias=isAlias;exports2.isCollection=isCollection;exports2.isDocument=isDocument2;exports2.isMap=isMap;exports2.isNode=isNode2;exports2.isPair=isPair;exports2.isScalar=isScalar;exports2.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(exports2){"use strict";var identity2=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit2(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}__name(visit2,"visit");visit2.BREAK=BREAK;visit2.SKIP=SKIP;visit2.REMOVE=REMOVE;function visit_(key,node,visitor,path53){let ctrl=callVisitor(key,node,visitor,path53);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path53,ctrl),visit_(key,ctrl,visitor,path53);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path53=Object.freeze(path53.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path53);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path53=Object.freeze(path53.concat(node));let ck=visit_("key",node.key,visitor,path53);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path53);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visit_,"visit_");async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}__name(visitAsync,"visitAsync");visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path53){let ctrl=await callVisitor(key,node,visitor,path53);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path53,ctrl),visitAsync_(key,ctrl,visitor,path53);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path53=Object.freeze(path53.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path53);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path53=Object.freeze(path53.concat(node));let ck=await visitAsync_("key",node.key,visitor,path53);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path53);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visitAsync_,"visitAsync_");function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}__name(initVisitor,"initVisitor");function callVisitor(key,node,visitor,path53){if(typeof visitor=="function")return visitor(key,node,path53);if(identity2.isMap(node))return visitor.Map?.(key,node,path53);if(identity2.isSeq(node))return visitor.Seq?.(key,node,path53);if(identity2.isPair(node))return visitor.Pair?.(key,node,path53);if(identity2.isScalar(node))return visitor.Scalar?.(key,node,path53);if(identity2.isAlias(node))return visitor.Alias?.(key,node,path53)}__name(callVisitor,"callVisitor");function replaceNode(key,path53,node){let parent2=path53[path53.length-1];if(identity2.isCollection(parent2))parent2.items[key]=node;else if(identity2.isPair(parent2))key==="key"?parent2.key=node:parent2.value=node;else if(identity2.isDocument(parent2))parent2.contents=node;else{let pt2=identity2.isAlias(parent2)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}__name(replaceNode,"replaceNode");exports2.visit=visit2;exports2.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=__name(tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),"escapeTagName"),Directives=class _Directives{static{__name(this,"Directives")}constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity2.isNode(doc.contents)){let tags={};visit2.visit(doc.contents,(_key,node)=>{identity2.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
68
68
|
`)}};Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports2.Directives=Directives}});var require_anchors=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/anchors.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw new Error(msg)}return!0}__name(anchorIsValid,"anchorIsValid");function anchorNames(root2){let anchors=new Set;return visit2.visit(root2,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}__name(anchorNames,"anchorNames");function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}__name(findNewAnchor,"findNewAnchor");function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:__name(source=>{aliasObjects.push(source),prevAnchors??(prevAnchors=anchorNames(doc));let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},"onAnchor"),setAnchors:__name(()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref=="object"&&ref.anchor&&(identity2.isScalar(ref.node)||identity2.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=new Error("Failed to resolve repeated object (this should not happen)");throw error.source=source,error}}},"setAnchors"),sourceObjects}}__name(createNodeAnchors,"createNodeAnchors");exports2.anchorIsValid=anchorIsValid;exports2.anchorNames=anchorNames;exports2.createNodeAnchors=createNodeAnchors;exports2.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/applyReviver.js"(exports2){"use strict";function applyReviver(reviver,obj,key,val2){if(val2&&typeof val2=="object")if(Array.isArray(val2))for(let i=0,len=val2.length;i<len;++i){let v0=val2[i],v1=applyReviver(reviver,val2,String(i),v0);v1===void 0?delete val2[i]:v1!==v0&&(val2[i]=v1)}else if(val2 instanceof Map)for(let k of Array.from(val2.keys())){let v0=val2.get(k),v1=applyReviver(reviver,val2,k,v0);v1===void 0?val2.delete(k):v1!==v0&&val2.set(k,v1)}else if(val2 instanceof Set)for(let v0 of Array.from(val2)){let v1=applyReviver(reviver,val2,v0,v0);v1===void 0?val2.delete(v0):v1!==v0&&(val2.delete(v0),val2.add(v1))}else for(let[k,v0]of Object.entries(val2)){let v1=applyReviver(reviver,val2,k,v0);v1===void 0?delete val2[k]:v1!==v0&&(val2[k]=v1)}return reviver.call(obj,key,val2)}__name(applyReviver,"applyReviver");exports2.applyReviver=applyReviver}});var require_toJS=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/toJS.js"(exports2){"use strict";var identity2=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON=="function"){if(!ctx||!identity2.hasAnchor(value))return value.toJSON(arg,ctx);let data2={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data2),ctx.onCreate=res2=>{data2.res=res2,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value=="bigint"&&!ctx?.keep?Number(value):value}__name(toJS,"toJS");exports2.toJS=toJS}});var require_Node=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Node.js"(exports2){"use strict";var applyReviver=require_applyReviver(),identity2=require_identity(),toJS=require_toJS(),NodeBase=class{static{__name(this,"NodeBase")}constructor(type){Object.defineProperty(this,identity2.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity2.isDocument(doc))throw new TypeError("A document argument is required");let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this,"",ctx);if(typeof onAnchor=="function")for(let{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver=="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports2.NodeBase=NodeBase}});var require_Alias=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Alias.js"(exports2){"use strict";var anchors=require_anchors(),visit2=require_visit(),identity2=require_identity(),Node2=require_Node(),toJS=require_toJS(),Alias=class extends Node2.NodeBase{static{__name(this,"Alias")}constructor(source){super(identity2.ALIAS),this.source=source,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit2.visit(doc,{Node:__name((_key,node)=>{(identity2.isAlias(node)||identity2.hasAnchor(node))&&nodes.push(node)},"Node")}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let{anchors:anchors2,doc,maxAliasCount}=ctx,source=this.resolve(doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data2=anchors2.get(source);if(data2||(toJS.toJS(source,null,ctx),data2=anchors2.get(source)),data2?.res===void 0){let msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0&&(data2.count+=1,data2.aliasCount===0&&(data2.aliasCount=getAliasCount(doc,source,anchors2)),data2.count*data2.aliasCount>maxAliasCount)){let msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}return data2.res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity2.isAlias(node)){let source=node.resolve(doc),anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity2.isCollection(node)){let count=0;for(let item of node.items){let c2=getAliasCount(doc,item,anchors2);c2>count&&(count=c2)}return count}else if(identity2.isPair(node)){let kc=getAliasCount(doc,node.key,anchors2),vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}__name(getAliasCount,"getAliasCount");exports2.Alias=Alias}});var require_Scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Scalar.js"(exports2){"use strict";var identity2=require_identity(),Node2=require_Node(),toJS=require_toJS(),isScalarValue=__name(value=>!value||typeof value!="function"&&typeof value!="object","isScalarValue"),Scalar=class extends Node2.NodeBase{static{__name(this,"Scalar")}constructor(value){super(identity2.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports2.Scalar=Scalar;exports2.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/createNode.js"(exports2){"use strict";var Alias=require_Alias(),identity2=require_identity(),Scalar=require_Scalar(),defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){let match=tags.filter(t2=>t2.tag===tagName),tagObj=match.find(t2=>!t2.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t2=>t2.identify?.(value)&&!t2.format)}__name(findTagObject,"findTagObject");function createNode(value,tagName,ctx){if(identity2.isDocument(value)&&(value=value.contents),identity2.isNode(value))return value;if(identity2.isPair(value)){let map2=ctx.schema[identity2.MAP].createNode?.(ctx.schema,null,ctx);return map2.items.push(value),map2}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<"u"&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value=="object"){if(ref=sourceObjects.get(value),ref)return ref.anchor??(ref.anchor=onAnchor(value)),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith("!!")&&(tagName=defaultTagPrefix+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON=="function"&&(value=value.toJSON()),!value||typeof value!="object"){let node2=new Scalar.Scalar(value);return ref&&(ref.node=node2),node2}tagObj=value instanceof Map?schema[identity2.MAP]:Symbol.iterator in Object(value)?schema[identity2.SEQ]:schema[identity2.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from=="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}__name(createNode,"createNode");exports2.createNode=createNode}});var require_Collection=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Collection.js"(exports2){"use strict";var createNode=require_createNode(),identity2=require_identity(),Node2=require_Node();function collectionFromPath(schema,path53,value){let v=value;for(let i=path53.length-1;i>=0;--i){let k=path53[i];if(typeof k=="number"&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:__name(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema,sourceObjects:new Map})}__name(collectionFromPath,"collectionFromPath");var isEmptyPath=__name(path53=>path53==null||typeof path53=="object"&&!!path53[Symbol.iterator]().next().done,"isEmptyPath"),Collection=class extends Node2.NodeBase{static{__name(this,"Collection")}constructor(type,schema){super(type),Object.defineProperty(this,"schema",{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it2=>identity2.isNode(it2)||identity2.isPair(it2)?it2.clone(schema):it2),this.range&&(copy.range=this.range.slice()),copy}addIn(path53,value){if(isEmptyPath(path53))this.add(value);else{let[key,...rest]=path53,node=this.get(key,!0);if(identity2.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path53){let[key,...rest]=path53;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity2.isCollection(node))return node.deleteIn(rest);throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path53,keepScalar){let[key,...rest]=path53,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity2.isScalar(node)?node.value:node:identity2.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity2.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity2.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path53){let[key,...rest]=path53;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity2.isCollection(node)?node.hasIn(rest):!1}setIn(path53,value){let[key,...rest]=path53;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity2.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports2.Collection=Collection;exports2.collectionFromPath=collectionFromPath;exports2.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyComment.js"(exports2){"use strict";var stringifyComment=__name(str=>str.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}__name(indentComment,"indentComment");var lineComment=__name((str,indent,comment)=>str.endsWith(`
|
|
69
69
|
`)?indentComment(comment,indent):comment.includes(`
|
|
70
70
|
`)?`
|
|
@@ -225,13 +225,13 @@ ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}retur
|
|
|
225
225
|
`).length-1;this.output.write(import_sisteransi.cursor.move(-999,t2*-1))}render(){let t2=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t2!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=j(this._prevFrame,t2),s=A(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-s),n=Math.max(0,e.numLinesBefore-s),o=e.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t2;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,o-n)),this.output.write(import_sisteransi.erase.lines(1));let a=t2.split(`
|
|
226
226
|
`);this.output.write(a[o]),this._prevFrame=t2,this.output.write(import_sisteransi.cursor.move(0,a.length-o-1));return}else if(e.lines.length>1){if(i<n)o=i;else{let h=o-n;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let a=t2.split(`
|
|
227
227
|
`).slice(o);this.output.write(a.join(`
|
|
228
|
-
`)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,
|
|
228
|
+
`)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z82,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z82=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
|
|
229
229
|
`);h.push(x),f+=x.length}if(f>$2){let b=0,x=0,G2=f,M2=e-v,R2=__name((j2,D)=>et2(h,G2,j2,D,$2),"R");m?({lineCount:G2,removals:b}=R2(0,M2),G2>$2&&({lineCount:G2,removals:x}=R2(M2+1,h.length))):({lineCount:G2,removals:x}=R2(M2+1,h.length),G2>$2&&({lineCount:G2,removals:b}=R2(0,M2))),b>0&&(m=!0,h.splice(0,b)),x>0&&(g=!0,h.splice(h.length-x,x))}let C2=[];m&&C2.push(l);for(let b of h)for(let x of b)C2.push(x);return g&&C2.push(l),C2},"Y"),ot2=__name(e=>{let i=e.active??"Yes",s=e.inactive??"No";return new Q({active:i,inactive:s,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??u.withGuide,u2=`${V2(this.state)} `,n=r?`${t("gray",d2)} `:"",o=R(e.output,e.message,n,u2),c2=`${r?`${t("gray",d2)}
|
|
230
230
|
`:""}${o}
|
|
231
231
|
`,a=this.value?i:s;switch(this.state){case"submit":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t("dim",a)}`}case"cancel":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t(["strikethrough","dim"],a)}${r?`
|
|
232
|
-
${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",
|
|
232
|
+
${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z82)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
|
|
233
233
|
${t("cyan",d2)} `:`
|
|
234
|
-
`:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",
|
|
234
|
+
`:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z82)} ${s}`}
|
|
235
235
|
${$2}
|
|
236
236
|
`}}}}).prompt()},"ot"),O2={message:__name((e=[],{symbol:i=t("gray",d2),secondarySymbol:s=t("gray",d2),output:r=process.stdout,spacing:u2=1,withGuide:n}={})=>{let o=[],c2=n??u.withGuide,a=c2?s:"",l=c2?`${i} `:"",$2=c2?`${s} `:"";for(let p2=0;p2<u2;p2++)o.push(a);let y2=Array.isArray(e)?e:e.split(`
|
|
237
237
|
`);if(y2.length>0){let[p2,...m]=y2;p2.length>0?o.push(`${l}${p2}`):o.push(c2?i:"");for(let g of m)g.length>0?o.push(`${$2}${g}`):o.push(c2?s:"")}r.write(`${o.join(`
|
|
@@ -257,7 +257,7 @@ ${o}
|
|
|
257
257
|
`}}}}).prompt(),"bt"),Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")},re=__name((e,i)=>e.includes(`
|
|
258
258
|
`)?e.split(`
|
|
259
259
|
`).map(s=>i(s)).join(`
|
|
260
|
-
`):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",
|
|
260
|
+
`):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z82)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
|
|
261
261
|
`:""}${n}
|
|
262
262
|
`;switch(this.state){case"submit":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"selected"),c2);return`${o}${a}`}case"cancel":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"cancelled"),c2);return`${o}${a}${s?`
|
|
263
263
|
${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
|
|
@@ -373,7 +373,7 @@ return __eta.res;
|
|
|
373
373
|
`)}}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(`
|
|
374
374
|
`).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,`
|
|
375
375
|
`).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(path53){let res="";try{res=fs18.readFileSync(path53,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path53}`):err}return res}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={"&":"&","<":"<",">":">",'"':""","'":"'"};__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(path53){try{return JSON.parse(readFileSync4(path53,"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(`
|
|
376
|
-
`)}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 z82}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 path53 of schemaFiles){let fileUid=basename(path53,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path53)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path53,"utf-8"))}catch(error){errors.push(`${basename(path53)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path53)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path53)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path53)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path53)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path53)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
|
|
376
|
+
`)}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 z84}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 path53 of schemaFiles){let fileUid=basename(path53,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path53)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path53,"utf-8"))}catch(error){errors.push(`${basename(path53)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path53)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path53)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path53)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path53)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path53)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
|
|
377
377
|
- ${errors.join(`
|
|
378
378
|
- `)}
|
|
379
379
|
No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
|
|
@@ -386,7 +386,7 @@ ${imports}
|
|
|
386
386
|
export const content = {
|
|
387
387
|
${entries2}
|
|
388
388
|
} as const;
|
|
389
|
-
`}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=
|
|
389
|
+
`}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=z84.object({uid:z84.string().min(1),name:z84.string().min(1).optional(),isSingleton:z84.boolean().optional(),i18n:z84.object({enabled:z84.boolean().optional()}).optional(),groups:z84.array(z84.object({id:z84.string().min(1),label:z84.string().min(1),default:z84.boolean().optional()}).strict()).optional(),fields:z84.record(z84.string(),z84.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(`
|
|
390
390
|
`)}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(`
|
|
391
391
|
`);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
|
|
392
392
|
`);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
|
|
@@ -675,7 +675,7 @@ ${removed.map(r=>` ${r.skill} \u2192 ${r.agent}`).join(`
|
|
|
675
675
|
`)},"render"),hint:"Run `fimo skills get <name>` for a skill, or add `--ref <doc>` for a reference."})}function runningCliSource(){let version=getCliVersion();return{status:"ok",data:{root:SKILLS_ROOT,source:"running-cli",version,cliVersion:version}}}function resolveSkillsGetSource(name,cwd){if(name!=="fimo-code")return runningCliSource();let projectRoot=findProjectRoot(cwd);if(!projectRoot)return runningCliSource();let packageJsonPath=resolveProjectFimoPackageJson(projectRoot);if(!packageJsonPath)return{status:"error",code:"PROJECT_RUNTIME_NOT_INSTALLED",message:"The project-local fimo package is not installed, so version-matched code guidance is unavailable.",hint:"Install the project dependencies, then run `fimo skills get fimo-code` again."};let version="unknown";try{let pkg=JSON.parse(fs35.readFileSync(packageJsonPath,"utf8"));typeof pkg.version=="string"&&(version=pkg.version)}catch{}let root2=path34.join(path34.dirname(packageJsonPath),"assets","skills");return fs35.existsSync(path34.join(root2,"fimo-code","SKILL.md"))?{status:"ok",data:{root:root2,source:"project-runtime",version,cliVersion:getCliVersion()}}:{status:"error",code:"PROJECT_SKILL_UNAVAILABLE",message:`Project runtime fimo@${version} does not include version-matched fimo-code guidance.`,hint:"Upgrade the project runtime, then run `fimo skills get fimo-code` again."}}function formatSkillStamp(skillName,refId,source,ctx){let separator=ctx.ascii?" | ":" \xB7 ",subject=refId?`${skillName} (references/${refId})`:skillName,origin=source.source==="project-runtime"?[`project runtime fimo@${source.version}`,`CLI fimo@${source.cliVersion}`]:[`running CLI fimo@${source.version}`];return[subject,...origin].join(separator)}function stampedSkillBody(stamp,content2,ctx){let rule=(ctx.ascii?"-":"\u2500").repeat(stamp.length);return`${stamp}
|
|
676
676
|
${rule}
|
|
677
677
|
${content2}`}function resolveProjectFimoPackageJson(projectRoot){let requireFromProject=createRequire3(path34.join(projectRoot,"package.json")),ancestorNodeModules=new Set,directory=projectRoot;for(;;){ancestorNodeModules.add(path34.join(directory,"node_modules"));let parent2=path34.dirname(directory);if(parent2===directory)break;directory=parent2}for(let searchRoot of requireFromProject.resolve.paths("fimo")??[]){if(!ancestorNodeModules.has(path34.normalize(searchRoot)))continue;let packageJsonPath=path34.join(searchRoot,"fimo","package.json");if(fs35.existsSync(packageJsonPath))return packageJsonPath}}function normalizeRef(ref){return ref.trim().replace(/\\/g,"/").replace(/^references\//,"").replace(/\.md$/,"")}function skillsGetCommand(name,options={}){let source=resolveSkillsGetSource(name,path34.resolve(options.cwd??process.cwd()));if(source.status==="error"){ui.error({command:"skills get",code:source.code,message:source.message,hint:source.hint});return}let skills2=discoverBundledSkills(source.data.root),skill=skills2.find(s=>s.name===name);if(!skill){ui.error({command:"skills get",code:"SKILL_NOT_FOUND",message:`Unknown skill "${name}".`,hint:skills2.length?`Available: ${skills2.map(s=>s.name).join(", ")}. Run \`fimo skills list\`.`:"No bundled skills found \u2014 try reinstalling fimo."});return}let targetPath,refId=null;if(options.ref){refId=normalizeRef(options.ref);let refsRoot=path34.resolve(skill.dir,"references"),candidate=path34.resolve(refsRoot,`${refId}.md`);if(!(candidate===refsRoot||candidate.startsWith(refsRoot+path34.sep))||!fs35.existsSync(candidate)){ui.error({command:"skills get",code:"SKILL_REF_NOT_FOUND",message:`Reference "${options.ref}" not found in skill "${skill.name}".`,hint:skill.refs.length?`Available refs: ${skill.refs.join(", ")}.`:"This skill has no reference docs."});return}targetPath=candidate}else targetPath=path34.join(skill.dir,"SKILL.md");let content2=fs35.readFileSync(targetPath,"utf8");ui.result({command:"skills get",data:{skill:skill.name,ref:refId,path:targetPath,content:content2,source:source.data.source,version:source.data.version,cliVersion:source.data.cliVersion},render:__name(ctx=>stampedSkillBody(formatSkillStamp(skill.name,refId,source.data,ctx),content2,ctx),"render"),hint:STREAMED_REFERENCE_HINT})}var SKILLS_ROOT,BOOTSTRAP_SKILL_NAME,BOOTSTRAP_SKILL_SOURCE,STREAMED_REFERENCE_HINT,STALE_GLOBAL_SKILL_NAMES,DETECTABLE_FIMO_SKILL_NAMES,init_skills=__esm({"src/cli/commands/skills.ts"(){init_dist5();init_dist();init_dist8();init_config();init_agents();init_project();init_version();SKILLS_ROOT=path34.resolve(CLI_ROOT,"assets","skills"),BOOTSTRAP_SKILL_NAME="fimo",BOOTSTRAP_SKILL_SOURCE=path34.join(SKILLS_ROOT,BOOTSTRAP_SKILL_NAME),STREAMED_REFERENCE_HINT="Reference paths in this document are identifiers, not project files. Load one with `fimo skills get <skill> --ref <reference>`.",STALE_GLOBAL_SKILL_NAMES=["fimo-cli","fimo-studio","fimo-migration","fimo-migrate","fimo-source-migrate"],DETECTABLE_FIMO_SKILL_NAMES=[BOOTSTRAP_SKILL_NAME,...STALE_GLOBAL_SKILL_NAMES];__name(isPrettyMode,"isPrettyMode");__name(runSkillsInstall,"runSkillsInstall");__name(renderSkillsInstall,"renderSkillsInstall");__name(skillsInstallCommand,"skillsInstallCommand");__name(skillsSyncCommand,"skillsSyncCommand");__name(detectAgentsWithFimoSkills,"detectAgentsWithFimoSkills");__name(removeDirIfExists,"removeDirIfExists");__name(removeGlobalSkillDirs,"removeGlobalSkillDirs");__name(hasGlobalSkillInstalled,"hasGlobalSkillInstalled");__name(removeCanonicalSkillDirs,"removeCanonicalSkillDirs");__name(cleanupStaleGlobalSkills,"cleanupStaleGlobalSkills");__name(skillsUninstallCommand,"skillsUninstallCommand");__name(listReferenceDocs,"listReferenceDocs");__name(discoverBundledSkills,"discoverBundledSkills");__name(firstLine,"firstLine");__name(skillsListCommand,"skillsListCommand");__name(runningCliSource,"runningCliSource");__name(resolveSkillsGetSource,"resolveSkillsGetSource");__name(formatSkillStamp,"formatSkillStamp");__name(stampedSkillBody,"stampedSkillBody");__name(resolveProjectFimoPackageJson,"resolveProjectFimoPackageJson");__name(normalizeRef,"normalizeRef");__name(skillsGetCommand,"skillsGetCommand")}});import{execFile as execFile9,spawnSync as spawnSync2}from"node:child_process";import{readFile as readFile5,writeFile as writeFile2}from"node:fs/promises";import path35 from"node:path";import{promisify as promisify9}from"node:util";function explainCreateProjectError(error){return error instanceof ApiRequestError&&error.detail.includes('insert into "projects"')&&(error.detail.includes('"subdomain"')||error.detail.includes('"subdomain_updated_at"'))?["Project creation failed because the local API database schema looks out of date.","The server is trying to write the `projects.subdomain` fields, but your database likely has not applied the latest migration yet.","Run `cd apps/api && pnpm db:migrate`, restart the API if needed, then retry."].join(`
|
|
678
|
-
`):error instanceof Error?error.message:String(error)}async function scaffoldNewProject(args){let{api,cfg,targetDir,displayName,options}=args,organizationId=await resolveOrganization(api,options.org),createSpinner=spinner("Creating Fimo project"),project;try{project=await api.createProject({organizationId,displayName:displayName??path35.basename(targetDir)})}catch(error){throw createSpinner.fail("Project creation failed"),new ScaffoldError("PROJECT_CREATE_FAILED",explainCreateProjectError(error))}createSpinner.succeed(`Project ${project.displayName??project.name} created (${project.id})`);let releaseAbort=installAbortHandler(api,project.id,project.name);try{return{scaffold:await scaffoldIntoProject({project,api,cfg,targetDir,options}),releaseAbort}}catch(error){throw releaseAbort(),error}}async function scaffoldIntoProject(args){let{project,api,cfg,targetDir,options}=args,remoteSp=spinner("Fetching git remote"),remote=await api.getGitRemote(project.id,MAIN_BRANCH);remoteSp.succeed("Remote ready");let selectedAgents;try{selectedAgents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills})}catch(err){throw new ScaffoldError("AGENT_SELECTION_FAILED",err instanceof Error?err.message:String(err))}let scaffoldSp=spinner("Scaffolding template"),framework=resolveTemplateFramework(options.framework),templateRoot=options.templateRoot?path35.resolve(options.templateRoot):process.env.FIMO_TEMPLATE_ROOT?path35.resolve(process.env.FIMO_TEMPLATE_ROOT):resolveTemplateRoot(framework);await copyTemplate(templateRoot,targetDir),seedSiteName({targetDir,project}),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl});let gitSp=spinner("Initializing git repository");await runGit(["init","-b",MAIN_BRANCH],targetDir),await ensureFimoRemote(targetDir,remote.url),gitSp.succeed("Git initialized with `fimo` remote"),scaffoldSp.succeed("Template scaffolded");let relativeTarget=path35.relative(process.cwd(),targetDir)||".";return{project,targetDir,relativeTarget,selectedAgents,tenantApiUrl:remote.tenantApiUrl}}async function finalizeInitialCommit(args){let{targetDir}=args,gitSp=spinner("Creating the initial commit");await runGit(["add","-A"],targetDir),await runGit(["commit","-m","chore: scaffold Fimo project"],targetDir).catch(()=>{}),gitSp.succeed("Initial commit created");let pushSp=spinner("Pushing initial commit to Fimo");try{return await runGit(["push","fimo",`HEAD:${MAIN_BRANCH}`],targetDir),pushSp.succeed("Initial commit pushed"),{pushedInitial:!0}}catch(error){pushSp.fail("Initial push failed");let failure=classifyPushError(error),retryHint=failure.kind==="auth"?"Sign in with `fimo login`, then run `fimo deploy` to push it.":"Run `fimo deploy` later to retry.";return O2.error(`Could not push the initial commit. ${retryHint}
|
|
678
|
+
`):error instanceof Error?error.message:String(error)}async function scaffoldNewProject(args){let{api,cfg,targetDir,displayName,options}=args,organizationId=await resolveOrganization(api,options.org),createSpinner=spinner("Creating Fimo project"),project;try{project=await api.createProject({organizationId,displayName:displayName??path35.basename(targetDir),origin:options.origin})}catch(error){throw createSpinner.fail("Project creation failed"),new ScaffoldError("PROJECT_CREATE_FAILED",explainCreateProjectError(error))}createSpinner.succeed(`Project ${project.displayName??project.name} created (${project.id})`);let releaseAbort=installAbortHandler(api,project.id,project.name);try{return{scaffold:await scaffoldIntoProject({project,api,cfg,targetDir,options}),releaseAbort}}catch(error){throw releaseAbort(),error}}async function scaffoldIntoProject(args){let{project,api,cfg,targetDir,options}=args,remoteSp=spinner("Fetching git remote"),remote=await api.getGitRemote(project.id,MAIN_BRANCH);remoteSp.succeed("Remote ready");let selectedAgents;try{selectedAgents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills})}catch(err){throw new ScaffoldError("AGENT_SELECTION_FAILED",err instanceof Error?err.message:String(err))}let scaffoldSp=spinner("Scaffolding template"),framework=resolveTemplateFramework(options.framework),templateRoot=options.templateRoot?path35.resolve(options.templateRoot):process.env.FIMO_TEMPLATE_ROOT?path35.resolve(process.env.FIMO_TEMPLATE_ROOT):resolveTemplateRoot(framework);await copyTemplate(templateRoot,targetDir),seedSiteName({targetDir,project}),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl});let gitSp=spinner("Initializing git repository");await runGit(["init","-b",MAIN_BRANCH],targetDir),await ensureFimoRemote(targetDir,remote.url),gitSp.succeed("Git initialized with `fimo` remote"),scaffoldSp.succeed("Template scaffolded");let relativeTarget=path35.relative(process.cwd(),targetDir)||".";return{project,targetDir,relativeTarget,selectedAgents,tenantApiUrl:remote.tenantApiUrl}}async function finalizeInitialCommit(args){let{targetDir}=args,gitSp=spinner("Creating the initial commit");await runGit(["add","-A"],targetDir),await runGit(["commit","-m","chore: scaffold Fimo project"],targetDir).catch(()=>{}),gitSp.succeed("Initial commit created");let pushSp=spinner("Pushing initial commit to Fimo");try{return await runGit(["push","fimo",`HEAD:${MAIN_BRANCH}`],targetDir),pushSp.succeed("Initial commit pushed"),{pushedInitial:!0}}catch(error){pushSp.fail("Initial push failed");let failure=classifyPushError(error),retryHint=failure.kind==="auth"?"Sign in with `fimo login`, then run `fimo deploy` to push it.":"Run `fimo deploy` later to retry.";return O2.error(`Could not push the initial commit. ${retryHint}
|
|
679
679
|
${failure.stderr||""}`.trim()),{pushedInitial:!1}}}function installAbortHandler(api,projectId,projectName){let cleaningUp=!1,handler=__name(()=>{cleaningUp&&(process.stderr.write(`
|
|
680
680
|
Force-exiting. Project may not have been fully cleaned up.
|
|
681
681
|
`),process.exit(130)),cleaningUp=!0,process.stderr.write(`
|
|
@@ -1145,9 +1145,9 @@ ${fontImport}@import 'tailwindcss';
|
|
|
1145
1145
|
max-width: 78rem;
|
|
1146
1146
|
}
|
|
1147
1147
|
`}function buildDesignDoc(manifest,theme,siteName){return[`${GENERATED_MARKER}`,`# ${siteName} design`,"","This file was generated by `fimo migrate apply` from the migration manifest.","","## Direction",`- Source platform: ${manifest.source.platform}`,`- Recommendation: ${manifest.recommendation.mode} - ${manifest.recommendation.reason}`,"","## Theme tokens",`- Background: \`${theme.background}\``,`- Foreground: \`${theme.foreground}\``,`- Primary: \`${theme.primary}\``,`- Accent: \`${theme.accent}\``,`- Secondary: \`${theme.secondary}\``,`- Radius: \`${theme.radius}\``,`- Display font: \`${theme.displayFont}\``,`- Body font: \`${theme.bodyFont}\``,"","## Extracted notes",...manifest.design.notes.length>0?manifest.design.notes.map(note=>`- ${note}`):["- No extra notes captured"],"","## Use this design file for","- refining the generated pages","- choosing final imagery","- tuning spacing and hierarchy","- aligning later CMS-driven components with the migrated visual system"].join(`
|
|
1148
|
-
`)}function planPages(pages2){let seenRoutes=new Set,seenNames=new Set,planned=[];for(let page of pages2){if(seenRoutes.has(page.route)||LEGAL_PAGE_MAP.has(page.route))continue;seenRoutes.add(page.route);let componentName=pageComponentName(page.route),suffix=2;for(;seenNames.has(componentName);)componentName=`${pageComponentName(page.route)}${suffix}`,suffix+=1;seenNames.add(componentName),planned.push({page,componentName,modulePath:path43.join(GENERATED_PAGES_DIR,`${componentName}.tsx`)})}return planned.some(item=>item.page.route==="/")||planned.unshift({page:{route:"/",url:manifestLikeUrl(pages2[0]?.url??"https://example.com","/"),title:"Home",kind:"marketing",seo:{title:"Home",description:null},headings:[],sections:[{id:"hero",label:"Hero",kind:"hero"},{id:"overview",label:"Overview",kind:"content-section"}],forms:[],imageCount:0,artifacts:{html:""},confidence:.3},componentName:"HomePage",modulePath:path43.join(GENERATED_PAGES_DIR,"HomePage.tsx")}),planned.sort((a,b)=>a.page.route==="/"?-1:b.page.route==="/"?1:a.page.route.localeCompare(b.page.route))}function selectNavPages(pages2){let topLevel=pages2.filter(page=>page.route==="/"?!0:LEGAL_PAGE_MAP.has(page.route)||page.kind==="blog-post"?!1:page.route.split("/").filter(Boolean).length<=1);return(topLevel.length>0?topLevel:pages2.filter(page=>page.route==="/"||page.kind!=="blog-post")).sort((a,b)=>a.route==="/"?-1:b.route==="/"?1:a.route.localeCompare(b.route)).slice(0,6)}function selectLegalRoutes(pages2){let found=pages2.map(page=>page.route).filter(routePath=>LEGAL_PAGE_MAP.has(routePath)),privacy=found.find(routePath=>routePath.includes("privacy"))??"/privacy",terms=found.find(routePath=>routePath.includes("terms"))??"/terms";return[privacy,terms]}function buildEntrySeed(cwd,page,collection){let data2={slug:page.route.split("/").filter(Boolean).pop()??"entry",title:page.title},extracted=extractPageSeedContent(cwd,page);if(collection.fields.includes("excerpt")){let excerpt=page.seo.description??extracted.paragraphs[0];excerpt&&(data2.excerpt=excerpt)}if(collection.fields.includes("body")&&(data2.body=buildRichTextFromPage(page,extracted)),collection.fields.includes("publishedAt")&&(data2.publishedAt=new Date().toISOString().slice(0,10)),collection.fields.includes("coverImage")){let coverImage=page.images?.[0]??extracted.images[0];coverImage&&(data2.coverImage={sourceUrl:coverImage.src,alt:coverImage.alt??page.title})}return data2}function extractPageSeedContent(cwd,page){let fallback={headings:page.headings,paragraphs:page.paragraphs??[],images:page.images??[]},htmlPath=page.artifacts.html?path43.resolve(cwd,page.artifacts.html):"";if(!htmlPath||!fs41.existsSync(htmlPath))return fallback;try{let $2=load(fs41.readFileSync(htmlPath,"utf8")),headings=unique($2("h1, h2, h3").toArray().map(element=>cleanText($2(element).text())).filter(Boolean).slice(0,12)),paragraphs=unique($2("p").toArray().map(element=>cleanText($2(element).text())).filter(value=>value.length>=24).slice(0,20)),images=uniqueImageObjects($2("img[src]").toArray().map(element=>({src:absolutizeUrl($2(element).attr("src")??"",page.url),alt:cleanText($2(element).attr("alt")??"")||null})).filter(image=>!!image.src));return{headings:headings.length>0?headings:fallback.headings,paragraphs:paragraphs.length>0?paragraphs:fallback.paragraphs,images:images.length>0?images:fallback.images}}catch{return fallback}}function buildRichTextFromPage(page,extracted){let content2=[...extracted.headings.slice(0,4).map(heading=>({type:"heading",attrs:{level:2},content:[{type:"text",text:heading}]})),...extracted.paragraphs.slice(0,10).map(paragraph=>({type:"paragraph",content:[{type:"text",text:paragraph}]}))];return content2.length===0&&content2.push(...page.sections.map((section2,index2)=>({type:index2===0?"heading":"paragraph",...index2===0?{attrs:{level:2}}:{},content:[{type:"text",text:index2===0?section2.label:`Refine the ${section2.label.toLowerCase()} content for ${page.title} using the source snapshot at ${page.artifacts.html}.`}]}))),{type:"doc",content:content2}}function buildSectionBody(page,section2){return section2.kind==="hero"?`Recreate the main promise of ${page.title} here. Use the source snapshot as reference, then replace this provisional copy with final messaging and media.`:section2.kind==="testimonials"?`Use this block to restore the original proof points and social validation from ${page.title}.`:section2.kind==="pricing"?`Translate the original offer structure from ${page.title} into clearer pricing or plan language inside Fimo.`:section2.kind==="contact"?`This section mirrors the original contact journey from ${page.title}. Replace the builder backend with a live Fimo form before publishing.`:`This section rebuilds the original ${section2.label.toLowerCase()} narrative from ${page.title} inside Fimo. Refine the final copy, layout, and media here.`}function buildFormBody(form){return`A draft Fimo form config was generated for this route with ${form.fields.length} field${form.fields.length===1?"":"s"}. Push it before wiring a live form component.`}function buildCallToActionTitle(page){return page.kind==="blog-post"?"Turn this article structure into a repeatable content system":page.kind==="contact"?"Replace the builder workflow with a live Fimo submission flow":"Refine the migrated structure into a polished Fimo experience"}function buildCallToActionBody(page,siteName){return page.kind==="blog-post"?`This article route was restored from the source site for ${siteName}. The next step is connecting it to real CMS entries and richer editorial content.`:`The route structure, theme, and provisional content for ${page.title} are now in place. Replace the scaffold text with final brand copy, assets, and CMS-backed content.`}function defaultSectionsForPage(page){return[{id:"overview",label:`${page.title} overview`,kind:"content-section"},{id:"highlights",label:`${page.title} highlights`,kind:"feature-grid"}]}function pageDescription(page,siteName){return page.seo.description??`This page recreates the original ${page.title} experience from the source site for ${siteName} and is ready for deeper Fimo customization.`}function pageEyebrow(page){return page.kind==="blog-post"?"Migrated article":page.kind==="contact"?"Contact route":page.kind==="legal"?"Legal page":page.route==="/"?"Migrated homepage":"Migrated page"}function navLabel(page){return page.route==="/"?"Home":page.title||titleize2(page.route.split("/").filter(Boolean).pop()??"Page")}function routeId(routePath){return slugify(routePath==="/"?"home":routePath.replace(/^\//,"").replace(/\//g,"-"))||"page"}function routeToKey(routePath){return routePath==="/"?"home":routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>slugify(part)).join(".")}function pageComponentName(routePath){if(routePath==="/")return"HomePage";let normalized=`${routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>titleize2(part).replace(/\s+/g,"")).join("")||"Page"}Page`;return/^[A-Za-z_$]/.test(normalized)?normalized:`Route${normalized}`}function sectionKeyFromLabel(label,index2){return slugify(label)||`section-${index2+1}`}function pluralLabelForSchema(collection){let singular=titleize2(collection.suggestedSchema.replace(/([a-z0-9])([A-Z])/g,"$1 $2"));return singular.endsWith("s")?singular:`${singular}s`}function fieldTypeForSchemaField(fieldName){let lower=fieldName.toLowerCase();return lower==="body"||lower==="content"||lower==="description"?"richtext":lower==="coverimage"||lower==="heroimage"||lower.endsWith("image")?"media":"string"}function normalizeFormFieldType(kind){let lower=kind.toLowerCase();return lower==="email"?"email":lower==="textarea"?"textarea":lower==="number"?"number":lower==="phone"||lower==="tel"||lower==="telephone"?"phone":lower==="url"?"url":lower==="checkbox"?"checkbox":lower==="date"?"date":lower==="hidden"?"hidden":lower==="file"?"file":lower==="select"||lower==="radio"?"select":"text"}function deriveSiteName(manifest){let homeTitle=manifest.pages.find(page=>page.route==="/")?.seo.title||manifest.pages[0]?.seo.title;if(homeTitle){let trimmed=homeTitle.split(/[-|:]/)[0]?.trim();if(trimmed)return trimmed}return titleize2(manifest.project.name.replace(/[-_]+/g," "))}function pickBodyFont(manifest){return manifest.design.tokens.fonts.find(font=>font.role==="body")?.family||manifest.design.tokens.fonts[0]?.family||"Manrope"}function pickDisplayFont(manifest,bodyFont){return manifest.design.tokens.fonts.find(font=>font.role==="heading")?.family||manifest.design.tokens.fonts.find(font=>font.family!==bodyFont)?.family||bodyFont}function buildGoogleFontImport(families){return`@import url('https://fonts.googleapis.com/css2?${families.map(family=>`family=${encodeURIComponent(family).replace(/%20/g,"+")}:wght@400;500;600;700`).join("&")}&display=swap');`}function shouldImportFont(family){return family.length>0&&!GENERIC_FONTS.has(family.toLowerCase())}function quote(value){return JSON.stringify(value)}function quoteCssFontStack(family,serifFallback){let wrapped=family.includes(" ")?`'${family}'`:family;return serifFallback?`${wrapped}, ui-serif, Georgia, Cambria, 'Times New Roman', serif`:`${wrapped}, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`}function titleize2(value){return value.replace(/[-_]+/g," ").split(/\s+/).filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}function slugify(value){return value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function normalizeColorToken(value){let trimmed=value.trim();if(/^#[0-9a-fA-F]{3,8}$/.test(trimmed))return trimmed;let rgb=trimmed.match(/^rgba?\(([^)]+)\)$/i);if(rgb){let parts=rgb[1].split(",").map(part=>Number.parseFloat(part.trim())).filter(part=>Number.isFinite(part));if(parts.length>=3)return`rgb(${Math.round(parts[0])} ${Math.round(parts[1])} ${Math.round(parts[2])})`}return null}function withAlpha(color,alpha){let rgb=toRgb(color);return rgb?`rgb(${rgb.r} ${rgb.g} ${rgb.b} / ${alpha})`:color}function getLuminance(color){let rgb=toRgb(color);if(!rgb)return null;let channels=[rgb.r,rgb.g,rgb.b].map(channel=>{let normalized=channel/255;return normalized<=.03928?normalized/12.92:((normalized+.055)/1.055)**2.4});return .2126*channels[0]+.7152*channels[1]+.0722*channels[2]}function toRgb(color){let hex=color.match(/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i);if(hex){let value=hex[1];return value.length===3&&(value=value.split("").map(part=>`${part}${part}`).join("")),value.length===8&&(value=value.slice(0,6)),{r:Number.parseInt(value.slice(0,2),16),g:Number.parseInt(value.slice(2,4),16),b:Number.parseInt(value.slice(4,6),16)}}let rgb=color.match(/^rgb\(([^)]+)\)$/i);if(rgb){let parts=rgb[1].trim().split(/\s+/).map(part=>Number.parseFloat(part)).filter(part=>Number.isFinite(part));if(parts.length>=3)return{r:Math.round(parts[0]),g:Math.round(parts[1]),b:Math.round(parts[2])}}return null}function readArtifactIndex(cwd){let artifactPath=path43.join(cwd,GENERATED_ROOT,"artifacts.json");if(!fs41.existsSync(artifactPath))return null;try{return JSON.parse(fs41.readFileSync(artifactPath,"utf8"))}catch{return null}}function cleanupPreviousArtifacts(cwd,index2){if(index2)for(let relativePath of[...index2.schemaFiles,...index2.formFiles,...index2.pageFiles,...index2.componentFiles,...index2.generatedFiles])deleteIfExists(path43.join(cwd,relativePath))}function writeFile3(cwd,relativePath,content2,written){let absolutePath=path43.join(cwd,relativePath);ensureDir(path43.dirname(absolutePath)),fs41.writeFileSync(absolutePath,content2,"utf8"),written.push(absolutePath)}function ensureDir(dir){fs41.mkdirSync(dir,{recursive:!0})}function resetDir(dir){fs41.rmSync(dir,{recursive:!0,force:!0}),fs41.mkdirSync(dir,{recursive:!0})}function deleteIfExists(filePath){fs41.existsSync(filePath)&&fs41.rmSync(filePath,{recursive:!0,force:!0})}function unique(values){return[...new Set(values)]}function uniqueImageObjects(images){let seen=new Set,results=[];for(let image of images)seen.has(image.src)||(seen.add(image.src),results.push(image));return results}function cleanText(value){return value.replace(/\s+/g," ").trim()}function absolutizeUrl(value,base){if(!value)return null;try{return new URL(value,base).toString()}catch{return null}}function toPosix(value){return value.split(path43.sep).join("/")}function manifestLikeUrl(seedUrl,routePath){try{let url=new URL(seedUrl);return url.pathname=routePath,url.toString()}catch{return`https://example.com${routePath}`}}var GENERATED_MARKER,MIGRATION_DIR,GENERATED_ROOT,GENERATED_PAGES_DIR,GENERATED_COMPONENTS_DIR,SCHEMAS_DIR,FORMS_DIR,GENERIC_FONTS,LEGAL_PAGE_MAP,init_migrate_apply=__esm({"src/cli/commands/migrate-apply.ts"(){init_slim();init_sync_forms();init_sync_schemas();init_project();GENERATED_MARKER="/* AUTO-GENERATED by fimo migrate apply */",MIGRATION_DIR=path43.join(".fimo","migrations","current"),GENERATED_ROOT=path43.join(MIGRATION_DIR,"generated"),GENERATED_PAGES_DIR=path43.join("src","pages","migrated"),GENERATED_COMPONENTS_DIR=path43.join("src","components","migration"),SCHEMAS_DIR=path43.join("src","schemas"),FORMS_DIR=path43.join("src","forms"),GENERIC_FONTS=new Set(["arial","georgia","helvetica","monospace","sans-serif","serif","system-ui","times new roman","ui-sans-serif","ui-serif"]),LEGAL_PAGE_MAP=new Map([["/privacy","./pages/Privacy.tsx"],["/privacy-policy","./pages/Privacy.tsx"],["/terms","./pages/Terms.tsx"],["/terms-of-service","./pages/Terms.tsx"]]);__name(applyMigrationManifest,"applyMigrationManifest");__name(resolveApplyFramework,"resolveApplyFramework");__name(pickThemePalette,"pickThemePalette");__name(buildSchemaDefinition,"buildSchemaDefinition");__name(buildFormDefinition,"buildFormDefinition");__name(writeSchemas,"writeSchemas");__name(writeForms,"writeForms");__name(writeCollectionSeeds,"writeCollectionSeeds");__name(writeGeneratedNotes,"writeGeneratedNotes");__name(buildMigrationShellComponent,"buildMigrationShellComponent");__name(buildMigrationPageTemplateComponent,"buildMigrationPageTemplateComponent");__name(buildPageModule,"buildPageModule");__name(buildRoutesFile,"buildRoutesFile");__name(buildFimoConfig,"buildFimoConfig");__name(buildThemeCss,"buildThemeCss");__name(buildDesignDoc,"buildDesignDoc");__name(planPages,"planPages");__name(selectNavPages,"selectNavPages");__name(selectLegalRoutes,"selectLegalRoutes");__name(buildEntrySeed,"buildEntrySeed");__name(extractPageSeedContent,"extractPageSeedContent");__name(buildRichTextFromPage,"buildRichTextFromPage");__name(buildSectionBody,"buildSectionBody");__name(buildFormBody,"buildFormBody");__name(buildCallToActionTitle,"buildCallToActionTitle");__name(buildCallToActionBody,"buildCallToActionBody");__name(defaultSectionsForPage,"defaultSectionsForPage");__name(pageDescription,"pageDescription");__name(pageEyebrow,"pageEyebrow");__name(navLabel,"navLabel");__name(routeId,"routeId");__name(routeToKey,"routeToKey");__name(pageComponentName,"pageComponentName");__name(sectionKeyFromLabel,"sectionKeyFromLabel");__name(pluralLabelForSchema,"pluralLabelForSchema");__name(fieldTypeForSchemaField,"fieldTypeForSchemaField");__name(normalizeFormFieldType,"normalizeFormFieldType");__name(deriveSiteName,"deriveSiteName");__name(pickBodyFont,"pickBodyFont");__name(pickDisplayFont,"pickDisplayFont");__name(buildGoogleFontImport,"buildGoogleFontImport");__name(shouldImportFont,"shouldImportFont");__name(quote,"quote");__name(quoteCssFontStack,"quoteCssFontStack");__name(titleize2,"titleize");__name(slugify,"slugify");__name(normalizeColorToken,"normalizeColorToken");__name(withAlpha,"withAlpha");__name(getLuminance,"getLuminance");__name(toRgb,"toRgb");__name(readArtifactIndex,"readArtifactIndex");__name(cleanupPreviousArtifacts,"cleanupPreviousArtifacts");__name(writeFile3,"writeFile");__name(ensureDir,"ensureDir");__name(resetDir,"resetDir");__name(deleteIfExists,"deleteIfExists");__name(unique,"unique");__name(uniqueImageObjects,"uniqueImageObjects");__name(cleanText,"cleanText");__name(absolutizeUrl,"absolutizeUrl");__name(toPosix,"toPosix");__name(manifestLikeUrl,"manifestLikeUrl")}});import{spawnSync as spawnSync4}from"node:child_process";import fs42 from"node:fs";import path44 from"node:path";import{fileURLToPath as fileURLToPath6}from"node:url";function emitMigrateError(command,error,fallbackCode){if(error instanceof MigrateCancelled){ui.info({command,message:error.message});return}if(error instanceof MigrateCommandError){ui.error({command,code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}});return}ui.error({command,code:fallbackCode,message:error instanceof Error?error.message:String(error)})}async function crawlMigrationArtifacts(args){return buildMigrationArtifacts({project:loadProjectMetadata(args.projectRoot),sourceUrl:args.sourceUrl,maxPages:args.maxPages,maxAssets:args.maxAssets,downloadMedia:args.downloadMedia})}function isMigrationSourceUrl(value){let target=value.trim();return/^https?:\/\//i.test(target)?!0:/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?(\/|$)/i.test(target)}async function migrateInitCommand(targetArg,dirArg,options){let command="migrate init";if(options.projectId!==void 0||!targetArg||!isMigrationSourceUrl(targetArg)){try{let{receipt,scaffoldWarnings}=await runSourceBackedInit(targetArg??options.cwd,dirArg,options);ui.result({command,data:receipt,render:__name(()=>renderSourceInitReceipt(receipt),"render"),warnings:scaffoldWarnings.length>0?scaffoldWarnings:void 0,hint:"Load the fimo-migration skill (`fimo skills get fimo-migration`) and build the ledger at "+path44.join(receipt.migration_dir,"manifest.json")})}catch(error){emitMigrateError(command,error,"COMMAND_FAILED")}return}try{let{projectRoot,scaffoldWarnings}=await ensureMigrationProject(dirArg,options),sourceUrl=normalizeSourceUrl(targetArg),sp=spinner(`Scanning ${sourceUrl}`),manifest;try{manifest=await crawlMigrationArtifacts({projectRoot,sourceUrl,maxPages:parseMaxPages(options.maxPages),maxAssets:parseMaxAssets(options.maxAssets),downloadMedia:options.downloadMedia!==!1})}catch(error){throw sp.fail("Migration bootstrap failed"),error}sp.succeed(`Migration artifacts written to ${path44.join(projectRoot,MIGRATION_DIR2)}`),ui.result({command,data:manifest,render:__name(()=>renderManifestSummary(manifest),"render"),warnings:scaffoldWarnings.length>0?scaffoldWarnings:void 0,hint:`Read ${path44.join(projectRoot,MIGRATION_DIR2,"brief.md")}`})}catch(error){emitMigrateError(command,error,"MIGRATION_CRAWL_FAILED")}}async function migratePullCommand(options){let command="migrate pull";try{let projectRoot=requireProjectRoot(options.cwd),previous=readMigrationManifest(projectRoot),sp=spinner(`Refreshing ${previous.source.url}`),manifest;try{manifest=await crawlMigrationArtifacts({projectRoot,sourceUrl:previous.source.url,maxPages:parseMaxPages(options.maxPages,previous.crawl.maxPages),maxAssets:parseMaxAssets(options.maxAssets),downloadMedia:options.downloadMedia!==!1})}catch(error){throw sp.fail("Migration refresh failed"),error}sp.succeed(`Migration artifacts refreshed in ${path44.join(projectRoot,MIGRATION_DIR2)}`),ui.result({command,data:manifest,render:__name(()=>renderManifestSummary(manifest),"render")})}catch(error){emitMigrateError(command,error,"MIGRATION_CRAWL_FAILED")}}async function migrateRunCommand(sourceUrlArg,dirArg,options){let command="migrate";try{let{projectRoot,scaffoldWarnings}=await ensureMigrationProject(dirArg,options),sourceUrl=normalizeSourceUrl(sourceUrlArg),sp=spinner(`Step 1/3: crawling ${sourceUrl}`),manifest;try{manifest=await crawlMigrationArtifacts({projectRoot,sourceUrl,maxPages:parseMaxPages(options.maxPages),maxAssets:parseMaxAssets(options.maxAssets),downloadMedia:options.downloadMedia!==!1}),sp.succeed("Step 1/3: migration artifacts written")}catch(error){throw sp.fail("Step 1/3: migration bootstrap failed"),wrapMigrateError(error,"MIGRATION_CRAWL_FAILED")}sp=spinner("Step 2/3: applying agent-ready Fimo scaffold");let applied;try{applied=applyMigrationManifest({cwd:projectRoot,manifest}),sp.succeed("Step 2/3: migration scaffold written")}catch(error){throw sp.fail("Step 2/3: migration apply failed"),wrapMigrateError(error,"MIGRATION_APPLY_FAILED")}sp=spinner("Step 3/3: preparing visual refinement handoff");let refined;try{let{prepareMigrationRefineArtifacts:prepareMigrationRefineArtifacts2}=await Promise.resolve().then(()=>(init_migrate_refine(),migrate_refine_exports));refined=prepareMigrationRefineArtifacts2({cwd:projectRoot,manifest,focusRoute:options.route}),sp.succeed("Step 3/3: migration refinement pack written")}catch(error){throw sp.fail("Step 3/3: migration refine failed"),wrapMigrateError(error,"MIGRATION_REFINE_FAILED")}let runWarnings=[...scaffoldWarnings,...applied.warnings];ui.result({command,data:{projectRoot,manifest,apply:applied,refine:refined},render:__name(()=>[renderManifestSummary(manifest),"",renderApplyResult(projectRoot,applied),"",`Agent-ready migration draft prepared for ${projectRoot}`,"This is not the final visual rebuild yet. The CLI extracted the source, generated a scaffold, and wrote an agent handoff pack."].join(`
|
|
1149
|
-
`),"render"),warnings:runWarnings.length>0?runWarnings:void 0,hint:`Ask your coding agent to follow ${path44.join(
|
|
1150
|
-
`),"render"),warnings:linked?void 0:[`${projectRoot} is not linked to a Fimo project; the commands above will fail until it is. Link an owner-supplied project with \`fimo init ${projectRoot} --project-id <projectId>\` (or create one with \`fimo init ${projectRoot} --org <organizationId>\`).`]})}catch(error){emitMigrateError(command,error,"COMMAND_FAILED")}}function migrateManifestCommand(options){let args=[resolveProjectCwd(readStringOption(options,"cwd"))];options.output&&args.push("--output",options.output),options.fresh&&args.push("--fresh"),runBundledMigrationScript("migrate manifest","build-canonical-manifest.mjs",args,{headline:"Canonical migration manifest updated"})}function migrateReportCommand(options){let args=[resolveProjectCwd(readStringOption(options,"cwd"))];options.manifest&&args.push("--manifest",options.manifest),options.output&&args.push("--output",options.output),options.updateManifest===!1&&args.push("--no-update-manifest"),runBundledMigrationScript("migrate report","write-migration-report.mjs",args,{headline:"Migration QA report written"})}function runBundledMigrationScript(command,scriptName,args,opts){let scriptPath=path44.join(MIGRATION_SKILL_SCRIPTS_DIR,scriptName);if(!fs42.existsSync(scriptPath)){ui.error({command,code:"MIGRATION_HELPER_FAILED",message:`Migration helper script not found: ${scriptPath}`});return}let jsonMode=currentMode().format==="json",result=spawnSync4(process.execPath,[scriptPath,...args],{stdio:jsonMode?["inherit",2,2]:"inherit"});if(result.error){ui.error({command,code:"MIGRATION_HELPER_FAILED",message:`Migration helper failed to start: ${result.error.message}`});return}if(typeof result.status=="number"&&result.status!==0){ui.error({command,code:"MIGRATION_HELPER_FAILED",message:`Migration helper exited with status ${result.status}`}),process.exitCode=result.status;return}ui.ok({command,headline:opts.headline})}function readStringOption(options,name){let value=options[name];if(typeof value=="string")return value;let longName=`--${name.replace(/[A-Z]/g,char=>`-${char.toLowerCase()}`)}`,shortName=name==="cwd"?"-C":null,rawArgs=process.argv.slice(2);for(let i=0;i<rawArgs.length;i+=1){let arg=rawArgs[i];if(arg===longName||shortName&&arg===shortName)return rawArgs[i+1];if(arg.startsWith(`${longName}=`))return arg.slice(longName.length+1)}}function readDownloadedMedia(mediaMapPath){return JSON.parse(fs42.readFileSync(mediaMapPath,"utf8")).filter(asset=>asset.status==="downloaded"&&asset.localPath)}async function ensureMigrationProject(dirArg,options){if(!dirArg)return{projectRoot:requireProjectRoot(options.cwd),scaffoldWarnings:[]};let explicitDir=path44.resolve(dirArg),resolvedRoot=resolveProjectCwd(explicitDir);if(fs42.existsSync(resolveProjectSettingsPath(resolvedRoot)))return{projectRoot:resolvedRoot,scaffoldWarnings:[]};if(fs42.existsSync(explicitDir)&&fs42.readdirSync(explicitDir).length>0)throw new MigrateCommandError("DIRECTORY_NOT_EMPTY",`Refusing to initialize a migration in non-empty directory ${explicitDir}.`,{hint:"Pass a Fimo project directory or an empty/new directory."});let outcome=await runInit(explicitDir,{...options,framework:options.framework??"react-router",skills:!1});switch(outcome.status){case"ok":return{projectRoot:outcome.data.target_dir,scaffoldWarnings:outcome.warnings};case"cancelled":throw new MigrateCancelled;case"info":throw new MigrateCancelled(outcome.message);case"error":throw new MigrateCommandError(outcome.code,outcome.message,{...outcome.hint?{hint:outcome.hint}:{}})}}async function runSourceBackedInit(dirArg,extraArg,options){if(!dirArg||isMigrationSourceUrl(dirArg))throw new MigrateCommandError("DIRECTORY_REQUIRED",dirArg?"`--project-id` needs a target project directory, not a URL.":"A published source URL or a target project directory is required.",{hint:"Run `fimo migrate init <dir> --project-id <projectId>` (or `--org <organizationId>` to create a new project), or `fimo migrate init <url> [dir]` to crawl a live site."});if(extraArg!==void 0)throw new MigrateCommandError("DIRECTORY_REQUIRED","A source-backed migration takes a single target directory.",{hint:"Run `fimo migrate init <dir> --project-id <projectId>` or `fimo migrate init <url> <dir>`."});let explicitDir=path44.resolve(dirArg);if(fs42.existsSync(resolveProjectSettingsPath(explicitDir))){let settings=loadProjectSettings(explicitDir);if(options.projectId&&options.projectId!==settings.projectId)throw new MigrateCommandError("PROJECT_ID_MISMATCH",`${explicitDir} is already linked to project ${settings.projectId}, not ${options.projectId}.`,{hint:"Drop --project-id to reuse the existing link, or pass a different target directory."});let framework=assertRequestedFramework(explicitDir,options.framework);return{receipt:buildSourceInitReceipt(explicitDir,settings.projectId,settings.name,requireMigrateAuth(),framework),scaffoldWarnings:[]}}if(fs42.existsSync(explicitDir)&&fs42.readdirSync(explicitDir).length>0)throw new MigrateCommandError("DIRECTORY_NOT_EMPTY",`Refusing to set up a migration target in non-empty directory ${explicitDir}.`,{hint:"Pass a linked Fimo project directory or an empty/new directory."});let outcome=await runInit(dirArg,{...options,framework:options.framework??"react-router",skills:!1});switch(outcome.status){case"ok":{let creds=readCredentials(loadConfig());return{receipt:buildSourceInitReceipt(outcome.data.target_dir,outcome.data.project_id,outcome.data.project_name,creds?.user?.email??null,assertRequestedFramework(outcome.data.target_dir,options.framework)),scaffoldWarnings:outcome.warnings}}case"cancelled":throw new MigrateCancelled;case"info":throw new MigrateCancelled(outcome.message);case"error":throw new MigrateCommandError(outcome.code,outcome.message,{hint:outcome.code==="NOT_AUTHENTICATED"?"Run `fimo login` first, then re-run `fimo migrate init`.":outcome.hint})}}function requireMigrateAuth(){let creds=readCredentials(loadConfig());if(!creds?.access_token)throw new MigrateCommandError("NOT_AUTHENTICATED","You are not signed in to Fimo.",{hint
|
|
1148
|
+
`)}function planPages(pages2){let seenRoutes=new Set,seenNames=new Set,planned=[];for(let page of pages2){if(seenRoutes.has(page.route)||LEGAL_PAGE_MAP.has(page.route))continue;seenRoutes.add(page.route);let componentName=pageComponentName(page.route),suffix=2;for(;seenNames.has(componentName);)componentName=`${pageComponentName(page.route)}${suffix}`,suffix+=1;seenNames.add(componentName),planned.push({page,componentName,modulePath:path43.join(GENERATED_PAGES_DIR,`${componentName}.tsx`)})}return planned.some(item=>item.page.route==="/")||planned.unshift({page:{route:"/",url:manifestLikeUrl(pages2[0]?.url??"https://example.com","/"),title:"Home",kind:"marketing",seo:{title:"Home",description:null},headings:[],sections:[{id:"hero",label:"Hero",kind:"hero"},{id:"overview",label:"Overview",kind:"content-section"}],forms:[],imageCount:0,artifacts:{html:""},confidence:.3},componentName:"HomePage",modulePath:path43.join(GENERATED_PAGES_DIR,"HomePage.tsx")}),planned.sort((a,b)=>a.page.route==="/"?-1:b.page.route==="/"?1:a.page.route.localeCompare(b.page.route))}function selectNavPages(pages2){let topLevel=pages2.filter(page=>page.route==="/"?!0:LEGAL_PAGE_MAP.has(page.route)||page.kind==="blog-post"?!1:page.route.split("/").filter(Boolean).length<=1);return(topLevel.length>0?topLevel:pages2.filter(page=>page.route==="/"||page.kind!=="blog-post")).sort((a,b)=>a.route==="/"?-1:b.route==="/"?1:a.route.localeCompare(b.route)).slice(0,6)}function selectLegalRoutes(pages2){let found=pages2.map(page=>page.route).filter(routePath=>LEGAL_PAGE_MAP.has(routePath)),privacy=found.find(routePath=>routePath.includes("privacy"))??"/privacy",terms=found.find(routePath=>routePath.includes("terms"))??"/terms";return[privacy,terms]}function buildEntrySeed(cwd,page,collection){let data2={slug:page.route.split("/").filter(Boolean).pop()??"entry",title:page.title},extracted=extractPageSeedContent(cwd,page);if(collection.fields.includes("excerpt")){let excerpt=page.seo.description??extracted.paragraphs[0];excerpt&&(data2.excerpt=excerpt)}if(collection.fields.includes("body")&&(data2.body=buildRichTextFromPage(page,extracted)),collection.fields.includes("publishedAt")&&(data2.publishedAt=new Date().toISOString().slice(0,10)),collection.fields.includes("coverImage")){let coverImage=page.images?.[0]??extracted.images[0];coverImage&&(data2.coverImage={sourceUrl:coverImage.src,alt:coverImage.alt??page.title})}return data2}function extractPageSeedContent(cwd,page){let fallback={headings:page.headings,paragraphs:page.paragraphs??[],images:page.images??[]},htmlPath=page.artifacts.html?path43.resolve(cwd,page.artifacts.html):"";if(!htmlPath||!fs41.existsSync(htmlPath))return fallback;try{let $2=load(fs41.readFileSync(htmlPath,"utf8")),headings=unique($2("h1, h2, h3").toArray().map(element=>cleanText($2(element).text())).filter(Boolean).slice(0,12)),paragraphs=unique($2("p").toArray().map(element=>cleanText($2(element).text())).filter(value=>value.length>=24).slice(0,20)),images=uniqueImageObjects($2("img[src]").toArray().map(element=>({src:absolutizeUrl($2(element).attr("src")??"",page.url),alt:cleanText($2(element).attr("alt")??"")||null})).filter(image=>!!image.src));return{headings:headings.length>0?headings:fallback.headings,paragraphs:paragraphs.length>0?paragraphs:fallback.paragraphs,images:images.length>0?images:fallback.images}}catch{return fallback}}function buildRichTextFromPage(page,extracted){let content2=[...extracted.headings.slice(0,4).map(heading=>({type:"heading",attrs:{level:2},content:[{type:"text",text:heading}]})),...extracted.paragraphs.slice(0,10).map(paragraph=>({type:"paragraph",content:[{type:"text",text:paragraph}]}))];return content2.length===0&&content2.push(...page.sections.map((section2,index2)=>({type:index2===0?"heading":"paragraph",...index2===0?{attrs:{level:2}}:{},content:[{type:"text",text:index2===0?section2.label:`Refine the ${section2.label.toLowerCase()} content for ${page.title} using the source snapshot at ${page.artifacts.html}.`}]}))),{type:"doc",content:content2}}function buildSectionBody(page,section2){return section2.kind==="hero"?`Recreate the main promise of ${page.title} here. Use the source snapshot as reference, then replace this provisional copy with final messaging and media.`:section2.kind==="testimonials"?`Use this block to restore the original proof points and social validation from ${page.title}.`:section2.kind==="pricing"?`Translate the original offer structure from ${page.title} into clearer pricing or plan language inside Fimo.`:section2.kind==="contact"?`This section mirrors the original contact journey from ${page.title}. Replace the builder backend with a live Fimo form before publishing.`:`This section rebuilds the original ${section2.label.toLowerCase()} narrative from ${page.title} inside Fimo. Refine the final copy, layout, and media here.`}function buildFormBody(form){return`A draft Fimo form config was generated for this route with ${form.fields.length} field${form.fields.length===1?"":"s"}. Push it before wiring a live form component.`}function buildCallToActionTitle(page){return page.kind==="blog-post"?"Turn this article structure into a repeatable content system":page.kind==="contact"?"Replace the builder workflow with a live Fimo submission flow":"Refine the migrated structure into a polished Fimo experience"}function buildCallToActionBody(page,siteName){return page.kind==="blog-post"?`This article route was restored from the source site for ${siteName}. The next step is connecting it to real CMS entries and richer editorial content.`:`The route structure, theme, and provisional content for ${page.title} are now in place. Replace the scaffold text with final brand copy, assets, and CMS-backed content.`}function defaultSectionsForPage(page){return[{id:"overview",label:`${page.title} overview`,kind:"content-section"},{id:"highlights",label:`${page.title} highlights`,kind:"feature-grid"}]}function pageDescription(page,siteName){return page.seo.description??`This page recreates the original ${page.title} experience from the source site for ${siteName} and is ready for deeper Fimo customization.`}function pageEyebrow(page){return page.kind==="blog-post"?"Migrated article":page.kind==="contact"?"Contact route":page.kind==="legal"?"Legal page":page.route==="/"?"Migrated homepage":"Migrated page"}function navLabel(page){return page.route==="/"?"Home":page.title||titleize2(page.route.split("/").filter(Boolean).pop()??"Page")}function routeId(routePath){return slugify(routePath==="/"?"home":routePath.replace(/^\//,"").replace(/\//g,"-"))||"page"}function routeToKey(routePath){return routePath==="/"?"home":routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>slugify(part)).join(".")}function pageComponentName(routePath){if(routePath==="/")return"HomePage";let normalized=`${routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>titleize2(part).replace(/\s+/g,"")).join("")||"Page"}Page`;return/^[A-Za-z_$]/.test(normalized)?normalized:`Route${normalized}`}function sectionKeyFromLabel(label,index2){return slugify(label)||`section-${index2+1}`}function pluralLabelForSchema(collection){let singular=titleize2(collection.suggestedSchema.replace(/([a-z0-9])([A-Z])/g,"$1 $2"));return singular.endsWith("s")?singular:`${singular}s`}function fieldTypeForSchemaField(fieldName){let lower=fieldName.toLowerCase();return lower==="body"||lower==="content"||lower==="description"?"richtext":lower==="coverimage"||lower==="heroimage"||lower.endsWith("image")?"media":"string"}function normalizeFormFieldType(kind){let lower=kind.toLowerCase();return lower==="email"?"email":lower==="textarea"?"textarea":lower==="number"?"number":lower==="phone"||lower==="tel"||lower==="telephone"?"phone":lower==="url"?"url":lower==="checkbox"?"checkbox":lower==="date"?"date":lower==="hidden"?"hidden":lower==="file"?"file":lower==="select"||lower==="radio"?"select":"text"}function deriveSiteName(manifest){let homeTitle=manifest.pages.find(page=>page.route==="/")?.seo.title||manifest.pages[0]?.seo.title;if(homeTitle){let trimmed=homeTitle.split(/[-|:]/)[0]?.trim();if(trimmed)return trimmed}return titleize2(manifest.project.name.replace(/[-_]+/g," "))}function pickBodyFont(manifest){return manifest.design.tokens.fonts.find(font=>font.role==="body")?.family||manifest.design.tokens.fonts[0]?.family||"Manrope"}function pickDisplayFont(manifest,bodyFont){return manifest.design.tokens.fonts.find(font=>font.role==="heading")?.family||manifest.design.tokens.fonts.find(font=>font.family!==bodyFont)?.family||bodyFont}function buildGoogleFontImport(families){return`@import url('https://fonts.googleapis.com/css2?${families.map(family=>`family=${encodeURIComponent(family).replace(/%20/g,"+")}:wght@400;500;600;700`).join("&")}&display=swap');`}function shouldImportFont(family){return family.length>0&&!GENERIC_FONTS.has(family.toLowerCase())}function quote(value){return JSON.stringify(value)}function quoteCssFontStack(family,serifFallback){let wrapped=family.includes(" ")?`'${family}'`:family;return serifFallback?`${wrapped}, ui-serif, Georgia, Cambria, 'Times New Roman', serif`:`${wrapped}, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`}function titleize2(value){return value.replace(/[-_]+/g," ").split(/\s+/).filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}function slugify(value){return value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function normalizeColorToken(value){let trimmed=value.trim();if(/^#[0-9a-fA-F]{3,8}$/.test(trimmed))return trimmed;let rgb=trimmed.match(/^rgba?\(([^)]+)\)$/i);if(rgb){let parts=rgb[1].split(",").map(part=>Number.parseFloat(part.trim())).filter(part=>Number.isFinite(part));if(parts.length>=3)return`rgb(${Math.round(parts[0])} ${Math.round(parts[1])} ${Math.round(parts[2])})`}return null}function withAlpha(color,alpha){let rgb=toRgb(color);return rgb?`rgb(${rgb.r} ${rgb.g} ${rgb.b} / ${alpha})`:color}function getLuminance(color){let rgb=toRgb(color);if(!rgb)return null;let channels=[rgb.r,rgb.g,rgb.b].map(channel=>{let normalized=channel/255;return normalized<=.03928?normalized/12.92:((normalized+.055)/1.055)**2.4});return .2126*channels[0]+.7152*channels[1]+.0722*channels[2]}function toRgb(color){let hex=color.match(/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i);if(hex){let value=hex[1];return value.length===3&&(value=value.split("").map(part=>`${part}${part}`).join("")),value.length===8&&(value=value.slice(0,6)),{r:Number.parseInt(value.slice(0,2),16),g:Number.parseInt(value.slice(2,4),16),b:Number.parseInt(value.slice(4,6),16)}}let rgb=color.match(/^rgb\(([^)]+)\)$/i);if(rgb){let parts=rgb[1].trim().split(/\s+/).map(part=>Number.parseFloat(part)).filter(part=>Number.isFinite(part));if(parts.length>=3)return{r:Math.round(parts[0]),g:Math.round(parts[1]),b:Math.round(parts[2])}}return null}function readArtifactIndex(cwd){let artifactPath=path43.join(cwd,GENERATED_ROOT,"artifacts.json");if(!fs41.existsSync(artifactPath))return null;try{return JSON.parse(fs41.readFileSync(artifactPath,"utf8"))}catch{return null}}function cleanupPreviousArtifacts(cwd,index2){if(index2)for(let relativePath of[...index2.schemaFiles,...index2.formFiles,...index2.pageFiles,...index2.componentFiles,...index2.generatedFiles])deleteIfExists(path43.join(cwd,relativePath))}function writeFile3(cwd,relativePath,content2,written){let absolutePath=path43.join(cwd,relativePath);ensureDir(path43.dirname(absolutePath)),fs41.writeFileSync(absolutePath,content2,"utf8"),written.push(absolutePath)}function ensureDir(dir){fs41.mkdirSync(dir,{recursive:!0})}function resetDir(dir){fs41.rmSync(dir,{recursive:!0,force:!0}),fs41.mkdirSync(dir,{recursive:!0})}function deleteIfExists(filePath){fs41.existsSync(filePath)&&fs41.rmSync(filePath,{recursive:!0,force:!0})}function unique(values){return[...new Set(values)]}function uniqueImageObjects(images){let seen=new Set,results=[];for(let image of images)seen.has(image.src)||(seen.add(image.src),results.push(image));return results}function cleanText(value){return value.replace(/\s+/g," ").trim()}function absolutizeUrl(value,base){if(!value)return null;try{return new URL(value,base).toString()}catch{return null}}function toPosix(value){return value.split(path43.sep).join("/")}function manifestLikeUrl(seedUrl,routePath){try{let url=new URL(seedUrl);return url.pathname=routePath,url.toString()}catch{return`https://example.com${routePath}`}}var GENERATED_MARKER,MIGRATION_DIR,GENERATED_ROOT,GENERATED_PAGES_DIR,GENERATED_COMPONENTS_DIR,SCHEMAS_DIR,FORMS_DIR,GENERIC_FONTS,LEGAL_PAGE_MAP,init_migrate_apply=__esm({"src/cli/commands/migrate-apply.ts"(){init_slim();init_sync_forms();init_sync_schemas();init_project();GENERATED_MARKER="/* AUTO-GENERATED by fimo migrate apply */",MIGRATION_DIR=path43.join(".fimo","migrations","current"),GENERATED_ROOT=path43.join(MIGRATION_DIR,"generated"),GENERATED_PAGES_DIR=path43.join("src","pages","migrated"),GENERATED_COMPONENTS_DIR=path43.join("src","components","migration"),SCHEMAS_DIR=path43.join("src","schemas"),FORMS_DIR=path43.join("src","forms"),GENERIC_FONTS=new Set(["arial","georgia","helvetica","monospace","sans-serif","serif","system-ui","times new roman","ui-sans-serif","ui-serif"]),LEGAL_PAGE_MAP=new Map([["/privacy","./pages/Privacy.tsx"],["/privacy-policy","./pages/Privacy.tsx"],["/terms","./pages/Terms.tsx"],["/terms-of-service","./pages/Terms.tsx"]]);__name(applyMigrationManifest,"applyMigrationManifest");__name(resolveApplyFramework,"resolveApplyFramework");__name(pickThemePalette,"pickThemePalette");__name(buildSchemaDefinition,"buildSchemaDefinition");__name(buildFormDefinition,"buildFormDefinition");__name(writeSchemas,"writeSchemas");__name(writeForms,"writeForms");__name(writeCollectionSeeds,"writeCollectionSeeds");__name(writeGeneratedNotes,"writeGeneratedNotes");__name(buildMigrationShellComponent,"buildMigrationShellComponent");__name(buildMigrationPageTemplateComponent,"buildMigrationPageTemplateComponent");__name(buildPageModule,"buildPageModule");__name(buildRoutesFile,"buildRoutesFile");__name(buildFimoConfig,"buildFimoConfig");__name(buildThemeCss,"buildThemeCss");__name(buildDesignDoc,"buildDesignDoc");__name(planPages,"planPages");__name(selectNavPages,"selectNavPages");__name(selectLegalRoutes,"selectLegalRoutes");__name(buildEntrySeed,"buildEntrySeed");__name(extractPageSeedContent,"extractPageSeedContent");__name(buildRichTextFromPage,"buildRichTextFromPage");__name(buildSectionBody,"buildSectionBody");__name(buildFormBody,"buildFormBody");__name(buildCallToActionTitle,"buildCallToActionTitle");__name(buildCallToActionBody,"buildCallToActionBody");__name(defaultSectionsForPage,"defaultSectionsForPage");__name(pageDescription,"pageDescription");__name(pageEyebrow,"pageEyebrow");__name(navLabel,"navLabel");__name(routeId,"routeId");__name(routeToKey,"routeToKey");__name(pageComponentName,"pageComponentName");__name(sectionKeyFromLabel,"sectionKeyFromLabel");__name(pluralLabelForSchema,"pluralLabelForSchema");__name(fieldTypeForSchemaField,"fieldTypeForSchemaField");__name(normalizeFormFieldType,"normalizeFormFieldType");__name(deriveSiteName,"deriveSiteName");__name(pickBodyFont,"pickBodyFont");__name(pickDisplayFont,"pickDisplayFont");__name(buildGoogleFontImport,"buildGoogleFontImport");__name(shouldImportFont,"shouldImportFont");__name(quote,"quote");__name(quoteCssFontStack,"quoteCssFontStack");__name(titleize2,"titleize");__name(slugify,"slugify");__name(normalizeColorToken,"normalizeColorToken");__name(withAlpha,"withAlpha");__name(getLuminance,"getLuminance");__name(toRgb,"toRgb");__name(readArtifactIndex,"readArtifactIndex");__name(cleanupPreviousArtifacts,"cleanupPreviousArtifacts");__name(writeFile3,"writeFile");__name(ensureDir,"ensureDir");__name(resetDir,"resetDir");__name(deleteIfExists,"deleteIfExists");__name(unique,"unique");__name(uniqueImageObjects,"uniqueImageObjects");__name(cleanText,"cleanText");__name(absolutizeUrl,"absolutizeUrl");__name(toPosix,"toPosix");__name(manifestLikeUrl,"manifestLikeUrl")}});import{spawnSync as spawnSync4}from"node:child_process";import fs42 from"node:fs";import path44 from"node:path";import{fileURLToPath as fileURLToPath6}from"node:url";function emitMigrateError(command,error,fallbackCode){if(error instanceof MigrateCancelled){ui.info({command,message:error.message});return}if(error instanceof MigrateCommandError){ui.error({command,code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}});return}ui.error({command,code:fallbackCode,message:error instanceof Error?error.message:String(error)})}async function crawlMigrationArtifacts(args){return buildMigrationArtifacts({project:loadProjectMetadata(args.projectRoot),sourceUrl:args.sourceUrl,maxPages:args.maxPages,maxAssets:args.maxAssets,downloadMedia:args.downloadMedia})}function isMigrationSourceUrl(value){let target=value.trim();return/^https?:\/\//i.test(target)?!0:/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?(\/|$)/i.test(target)}async function migrateInitCommand(targetArg,dirArg,options){let command="migrate init";if(options.projectId!==void 0||!targetArg||!isMigrationSourceUrl(targetArg)){try{let{receipt,scaffoldWarnings}=await runSourceBackedInit(targetArg??options.cwd,dirArg,options);await reportMigration(receipt.project_id,"didStartMigration",{sourcePlatform:receipt.source_platform}),await reportMigration(receipt.project_id,"didEndMigration",{sourcePlatform:receipt.source_platform,success:!0});let warnings2=scaffoldWarnings;ui.result({command,data:receipt,render:__name(()=>renderSourceInitReceipt(receipt),"render"),warnings:warnings2.length>0?warnings2:void 0,hint:"Load the fimo-migration skill (`fimo skills get fimo-migration`) and build the ledger at "+path44.join(receipt.migration_dir,"manifest.json")})}catch(error){emitMigrateError(command,error,"COMMAND_FAILED")}return}let projectRoot,sourcePlatform="unknown",warnings=[];try{sourcePlatform=parseSourcePlatform(options.sourcePlatform);let target=await ensureMigrationProject(dirArg,options);projectRoot=target.projectRoot;let projectId=loadProjectMetadata(projectRoot).projectId;warnings.push(...target.scaffoldWarnings),await reportMigration(projectId,"didStartMigration",{sourcePlatform});let sourceUrl=normalizeSourceUrl(targetArg),sp=spinner(`Scanning ${sourceUrl}`),manifest;try{manifest=await crawlMigrationArtifacts({projectRoot,sourceUrl,maxPages:parseMaxPages(options.maxPages),maxAssets:parseMaxAssets(options.maxAssets),downloadMedia:options.downloadMedia!==!1})}catch(error){throw sp.fail("Migration bootstrap failed"),error}sp.succeed(`Migration artifacts written to ${path44.join(projectRoot,MIGRATION_DIR2)}`),sourcePlatform=crawledSourcePlatform(manifest,options),await reportMigration(projectId,"didEndMigration",{sourcePlatform,success:!0}),ui.result({command,data:manifest,render:__name(()=>renderManifestSummary(manifest),"render"),warnings:warnings.length>0?warnings:void 0,hint:`Read ${path44.join(projectRoot,MIGRATION_DIR2,"brief.md")}`})}catch(error){await reportMigrationFailure(projectRoot,sourcePlatform,error,"MIGRATION_CRAWL_FAILED"),emitMigrateError(command,error,"MIGRATION_CRAWL_FAILED")}}async function migratePullCommand(options){let command="migrate pull";try{let projectRoot=requireProjectRoot(options.cwd),previous=readMigrationManifest(projectRoot),sp=spinner(`Refreshing ${previous.source.url}`),manifest;try{manifest=await crawlMigrationArtifacts({projectRoot,sourceUrl:previous.source.url,maxPages:parseMaxPages(options.maxPages,previous.crawl.maxPages),maxAssets:parseMaxAssets(options.maxAssets),downloadMedia:options.downloadMedia!==!1})}catch(error){throw sp.fail("Migration refresh failed"),error}sp.succeed(`Migration artifacts refreshed in ${path44.join(projectRoot,MIGRATION_DIR2)}`),ui.result({command,data:manifest,render:__name(()=>renderManifestSummary(manifest),"render")})}catch(error){emitMigrateError(command,error,"MIGRATION_CRAWL_FAILED")}}async function migrateRunCommand(sourceUrlArg,dirArg,options){let command="migrate",projectRoot,sourcePlatform="unknown",runWarnings=[];try{sourcePlatform=parseSourcePlatform(options.sourcePlatform);let target=await ensureMigrationProject(dirArg,options);projectRoot=target.projectRoot;let root2=target.projectRoot,projectId=loadProjectMetadata(root2).projectId;runWarnings.push(...target.scaffoldWarnings),await reportMigration(projectId,"didStartMigration",{sourcePlatform});let sourceUrl=normalizeSourceUrl(sourceUrlArg),sp=spinner(`Step 1/3: crawling ${sourceUrl}`),manifest;try{manifest=await crawlMigrationArtifacts({projectRoot:root2,sourceUrl,maxPages:parseMaxPages(options.maxPages),maxAssets:parseMaxAssets(options.maxAssets),downloadMedia:options.downloadMedia!==!1}),sp.succeed("Step 1/3: migration artifacts written")}catch(error){throw sp.fail("Step 1/3: migration bootstrap failed"),wrapMigrateError(error,"MIGRATION_CRAWL_FAILED")}sp=spinner("Step 2/3: applying agent-ready Fimo scaffold");let applied;try{applied=applyMigrationManifest({cwd:root2,manifest}),sp.succeed("Step 2/3: migration scaffold written")}catch(error){throw sp.fail("Step 2/3: migration apply failed"),wrapMigrateError(error,"MIGRATION_APPLY_FAILED")}sp=spinner("Step 3/3: preparing visual refinement handoff");let refined;try{let{prepareMigrationRefineArtifacts:prepareMigrationRefineArtifacts2}=await Promise.resolve().then(()=>(init_migrate_refine(),migrate_refine_exports));refined=prepareMigrationRefineArtifacts2({cwd:root2,manifest,focusRoute:options.route}),sp.succeed("Step 3/3: migration refinement pack written")}catch(error){throw sp.fail("Step 3/3: migration refine failed"),wrapMigrateError(error,"MIGRATION_REFINE_FAILED")}sourcePlatform=crawledSourcePlatform(manifest,options),runWarnings.push(...applied.warnings),await reportMigration(projectId,"didEndMigration",{sourcePlatform,success:!0}),ui.result({command,data:{projectRoot:root2,manifest,apply:applied,refine:refined},render:__name(()=>[renderManifestSummary(manifest),"",renderApplyResult(root2,applied),"",`Agent-ready migration draft prepared for ${root2}`,"This is not the final visual rebuild yet. The CLI extracted the source, generated a scaffold, and wrote an agent handoff pack."].join(`
|
|
1149
|
+
`),"render"),warnings:runWarnings.length>0?runWarnings:void 0,hint:`Ask your coding agent to follow ${path44.join(root2,MIGRATION_DIR2,"refine","agent-prompt.md")}`})}catch(error){await reportMigrationFailure(projectRoot,sourcePlatform,error,"COMMAND_FAILED"),emitMigrateError(command,error,"COMMAND_FAILED")}}function wrapMigrateError(error,code2){return error instanceof MigrateCommandError?error:new MigrateCommandError(code2,error instanceof Error?error.message:String(error))}function migrateInspectCommand(options){let command="migrate inspect";try{let projectRoot=resolveProjectCwd(readStringOption(options,"cwd"));if(fs42.existsSync(path44.join(projectRoot,MIGRATION_DIR2,"manifest.json"))){let manifest=readMigrationManifest(projectRoot);ui.result({command,data:manifest,render:__name(()=>renderManifestSummary(manifest),"render")});return}let canonical=readCanonicalMigrationManifest(projectRoot);ui.result({command,data:canonical,render:__name(()=>renderCanonicalManifestSummary(projectRoot,canonical),"render")})}catch(error){emitMigrateError(command,error,"COMMAND_FAILED")}}function migrateApplyCommand(options){let command="migrate apply";try{let projectRoot=requireProjectRoot(readStringOption(options,"cwd")),manifest=readMigrationManifest(projectRoot),sp=spinner("Generating Fimo migration scaffold"),result;try{result=applyMigrationManifest({cwd:projectRoot,manifest})}catch(error){throw sp.fail("Migration apply failed"),error}sp.succeed("Migration scaffold written"),ui.result({command,data:result,render:__name(()=>renderApplyResult(projectRoot,result),"render"),warnings:result.warnings.length>0?result.warnings:void 0,hint:`Run \`fimo migrate refine -C ${projectRoot}\` or read ${path44.join(projectRoot,MIGRATION_DIR2,"generated","next-steps.md")}`})}catch(error){emitMigrateError(command,error,"MIGRATION_APPLY_FAILED")}}function migrateImportCommand(options){let command="migrate import";try{let projectRoot=resolveProjectCwd(readStringOption(options,"cwd")),linked=fs42.existsSync(resolveProjectSettingsPath(projectRoot)),mediaMapPath=path44.join(projectRoot,MIGRATION_DIR2,MEDIA_DIR,"map.json"),entriesDir=path44.join(projectRoot,MIGRATION_DIR2,"generated","entries"),schemasDir=path44.join(projectRoot,"src","schemas"),formsDir=path44.join(projectRoot,"src","forms"),media=fs42.existsSync(mediaMapPath)?readDownloadedMedia(mediaMapPath):[],schemas3=fs42.existsSync(schemasDir)?fs42.readdirSync(schemasDir).filter(name=>name.endsWith(".json")):[],forms3=fs42.existsSync(formsDir)?fs42.readdirSync(formsDir).filter(name=>name.endsWith(".json")):[],entryFiles=fs42.existsSync(entriesDir)?fs42.readdirSync(entriesDir).filter(name=>name.endsWith(".json")):[],entryCommands=entryFiles.map(file=>{let typeName=path44.basename(file,".json");return`Review ${path44.join(MIGRATION_DIR2,"generated","entries",file)}, then run fimo entries create ${typeName} --body '<entry-json>' -C ${projectRoot} for each approved entry`}),result={projectRoot,linked,media:media.length,schemas:schemas3.length,forms:forms3.length,entryFiles:entryFiles.length,commands:[...media.map(asset=>`fimo assets upload ${asset.localPath} -C ${projectRoot}`),...schemas3.map(file=>`fimo schemas push ${path44.basename(file,".json")} -C ${projectRoot}`),...forms3.map(file=>`fimo forms push ${path44.basename(file,".json")} -C ${projectRoot}`),...entryCommands]};ui.result({command,data:result,render:__name(()=>["`fimo migrate import` prints the import plan; it writes no data.","Review the generated files, then run the relevant commands below:",...result.commands.length===0?["- No generated media, schemas, forms, or entry suggestions were found."]:result.commands.map(line=>`- ${line}`)].join(`
|
|
1150
|
+
`),"render"),warnings:linked?void 0:[`${projectRoot} is not linked to a Fimo project; the commands above will fail until it is. Link an owner-supplied project with \`fimo init ${projectRoot} --project-id <projectId>\` (or create one with \`fimo init ${projectRoot} --org <organizationId>\`).`]})}catch(error){emitMigrateError(command,error,"COMMAND_FAILED")}}function migrateManifestCommand(options){let args=[resolveProjectCwd(readStringOption(options,"cwd"))];options.output&&args.push("--output",options.output),options.fresh&&args.push("--fresh"),runBundledMigrationScript("migrate manifest","build-canonical-manifest.mjs",args,{headline:"Canonical migration manifest updated"})}function migrateReportCommand(options){let args=[resolveProjectCwd(readStringOption(options,"cwd"))];options.manifest&&args.push("--manifest",options.manifest),options.output&&args.push("--output",options.output),options.updateManifest===!1&&args.push("--no-update-manifest"),runBundledMigrationScript("migrate report","write-migration-report.mjs",args,{headline:"Migration QA report written"})}function parseSourcePlatform(value){let normalized=value?.trim().toLowerCase();if(!normalized)return"unknown";let platform4=MIGRATION_SOURCE_PLATFORMS.find(candidate=>candidate===normalized);if(!platform4)throw new MigrateCommandError("SOURCE_PLATFORM_INVALID",`Unknown source platform "${value}".`,{hint:`Use one of: ${MIGRATION_SOURCE_PLATFORMS.join(", ")}.`});return platform4}function crawledSourcePlatform(manifest,options){return options.sourcePlatform?parseSourcePlatform(options.sourcePlatform):MIGRATION_SOURCE_PLATFORMS.find(candidate=>candidate===manifest.source.platform)??"unknown"}async function reportMigration(projectId,event,properties){try{await new FimoApiClient(loadConfig()).trackProjectEvent(projectId,event,properties)}catch{}}async function reportMigrationFailure(projectRoot,sourcePlatform,error,fallbackCode){if(!projectRoot)return;let projectId;try{projectId=loadProjectMetadata(projectRoot).projectId}catch{return}let code2=error instanceof MigrateCancelled?"CANCELLED":error instanceof MigrateCommandError?error.code:fallbackCode;await reportMigration(projectId,"didEndMigration",{sourcePlatform,success:!1,error:code2})}function runBundledMigrationScript(command,scriptName,args,opts){let scriptPath=path44.join(MIGRATION_SKILL_SCRIPTS_DIR,scriptName);if(!fs42.existsSync(scriptPath)){ui.error({command,code:"MIGRATION_HELPER_FAILED",message:`Migration helper script not found: ${scriptPath}`});return}let jsonMode=currentMode().format==="json",result=spawnSync4(process.execPath,[scriptPath,...args],{stdio:jsonMode?["inherit",2,2]:"inherit"});if(result.error){ui.error({command,code:"MIGRATION_HELPER_FAILED",message:`Migration helper failed to start: ${result.error.message}`});return}if(typeof result.status=="number"&&result.status!==0){ui.error({command,code:"MIGRATION_HELPER_FAILED",message:`Migration helper exited with status ${result.status}`}),process.exitCode=result.status;return}ui.ok({command,headline:opts.headline})}function readStringOption(options,name){let value=options[name];if(typeof value=="string")return value;let longName=`--${name.replace(/[A-Z]/g,char=>`-${char.toLowerCase()}`)}`,shortName=name==="cwd"?"-C":null,rawArgs=process.argv.slice(2);for(let i=0;i<rawArgs.length;i+=1){let arg=rawArgs[i];if(arg===longName||shortName&&arg===shortName)return rawArgs[i+1];if(arg.startsWith(`${longName}=`))return arg.slice(longName.length+1)}}function readDownloadedMedia(mediaMapPath){return JSON.parse(fs42.readFileSync(mediaMapPath,"utf8")).filter(asset=>asset.status==="downloaded"&&asset.localPath)}async function ensureMigrationProject(dirArg,options){if(!dirArg)return{projectRoot:requireProjectRoot(options.cwd),scaffoldWarnings:[]};let explicitDir=path44.resolve(dirArg),resolvedRoot=resolveProjectCwd(explicitDir);if(fs42.existsSync(resolveProjectSettingsPath(resolvedRoot)))return{projectRoot:resolvedRoot,scaffoldWarnings:[]};if(fs42.existsSync(explicitDir)&&fs42.readdirSync(explicitDir).length>0)throw new MigrateCommandError("DIRECTORY_NOT_EMPTY",`Refusing to initialize a migration in non-empty directory ${explicitDir}.`,{hint:"Pass a Fimo project directory or an empty/new directory."});let outcome=await runInit(explicitDir,{...options,framework:options.framework??"react-router",skills:!1,origin:"migration"});switch(outcome.status){case"ok":return{projectRoot:outcome.data.target_dir,scaffoldWarnings:outcome.warnings};case"cancelled":throw new MigrateCancelled;case"info":throw new MigrateCancelled(outcome.message);case"error":throw new MigrateCommandError(outcome.code,outcome.message,{...outcome.hint?{hint:outcome.hint}:{}})}}async function runSourceBackedInit(dirArg,extraArg,options){if(!dirArg||isMigrationSourceUrl(dirArg))throw new MigrateCommandError("DIRECTORY_REQUIRED",dirArg?"`--project-id` needs a target project directory, not a URL.":"A published source URL or a target project directory is required.",{hint:"Run `fimo migrate init <dir> --project-id <projectId>` (or `--org <organizationId>` to create a new project), or `fimo migrate init <url> [dir]` to crawl a live site."});if(extraArg!==void 0)throw new MigrateCommandError("DIRECTORY_REQUIRED","A source-backed migration takes a single target directory.",{hint:"Run `fimo migrate init <dir> --project-id <projectId>` or `fimo migrate init <url> <dir>`."});let sourcePlatform=parseSourcePlatform(options.sourcePlatform),explicitDir=path44.resolve(dirArg);if(fs42.existsSync(resolveProjectSettingsPath(explicitDir))){let settings=loadProjectSettings(explicitDir);if(options.projectId&&options.projectId!==settings.projectId)throw new MigrateCommandError("PROJECT_ID_MISMATCH",`${explicitDir} is already linked to project ${settings.projectId}, not ${options.projectId}.`,{hint:"Drop --project-id to reuse the existing link, or pass a different target directory."});let framework=assertRequestedFramework(explicitDir,options.framework);return{receipt:buildSourceInitReceipt(explicitDir,settings.projectId,settings.name,requireMigrateAuth(),framework,sourcePlatform),scaffoldWarnings:[]}}if(fs42.existsSync(explicitDir)&&fs42.readdirSync(explicitDir).length>0)throw new MigrateCommandError("DIRECTORY_NOT_EMPTY",`Refusing to set up a migration target in non-empty directory ${explicitDir}.`,{hint:"Pass a linked Fimo project directory or an empty/new directory."});let outcome=await runInit(dirArg,{...options,framework:options.framework??"react-router",skills:!1,origin:"migration"});switch(outcome.status){case"ok":{let creds=readCredentials(loadConfig());return{receipt:buildSourceInitReceipt(outcome.data.target_dir,outcome.data.project_id,outcome.data.project_name,creds?.user?.email??null,assertRequestedFramework(outcome.data.target_dir,options.framework),sourcePlatform),scaffoldWarnings:outcome.warnings}}case"cancelled":throw new MigrateCancelled;case"info":throw new MigrateCancelled(outcome.message);case"error":throw new MigrateCommandError(outcome.code,outcome.message,{hint:outcome.code==="NOT_AUTHENTICATED"?"Run `fimo login` first, then re-run `fimo migrate init`.":outcome.hint})}}function requireMigrateAuth(retryCommand3="fimo migrate init"){let creds=readCredentials(loadConfig());if(!creds?.access_token)throw new MigrateCommandError("NOT_AUTHENTICATED","You are not signed in to Fimo.",{hint:`Run \`fimo login\` first, then re-run \`${retryCommand3}\`.`});return creds.user?.email??null}function buildSourceInitReceipt(projectRoot,projectId,projectName,user,framework,sourcePlatform){let migrationDir=path44.join(projectRoot,CANONICAL_MIGRATION_DIR);return fs42.mkdirSync(migrationDir,{recursive:!0}),{mode:"source-backed",authenticated:!0,user,project_id:projectId,project_name:projectName,target_dir:projectRoot,migration_dir:migrationDir,framework,source_platform:sourcePlatform,ready:!0}}function readTargetFramework(projectRoot){let configPath=resolveProjectConfigPath(projectRoot);if(!fs42.existsSync(configPath))return null;try{let config=JSON.parse(fs42.readFileSync(configPath,"utf8"));return typeof config.runtime?.framework=="string"?config.runtime.framework:null}catch{return null}}function assertRequestedFramework(projectRoot,requestedFramework){let actualFramework=readTargetFramework(projectRoot);if(!requestedFramework)return actualFramework;let requested=requestedFramework.trim().toLowerCase();if(!actualFramework||actualFramework.trim().toLowerCase()!==requested)throw new MigrateCommandError("FRAMEWORK_MISMATCH",actualFramework?`Migration target uses ${actualFramework}, but ${requestedFramework} was requested.`:`Migration target does not declare runtime.framework, but ${requestedFramework} was requested.`,{hint:"Recreate or relink the target with the requested framework before importing migration data."});return actualFramework}function renderSourceInitReceipt(receipt){return["Mode: source-backed",`Auth: signed in${receipt.user?` as ${receipt.user}`:""}`,`Project: ${receipt.project_name} (${receipt.project_id})`,`Target: ${receipt.target_dir} (linked)`,`Framework: ${receipt.framework??"unknown"}`,`Source: ${receipt.source_platform}`,`Migration dir: ${receipt.migration_dir}`,"Ready: yes \u2014 no schemas, entries, assets, or forms were written"].join(`
|
|
1151
1151
|
`)}function requireProjectRoot(cwdOption){let root2=resolveProjectCwd(cwdOption);if(!fs42.existsSync(resolveProjectSettingsPath(root2)))throw new MigrateCommandError("NOT_IN_PROJECT","You are not in a Fimo project.",{hint:"Run `fimo init` first or pass a project directory to `fimo migrate init`."});return root2}function readMigrationManifest(projectRoot){let manifestPath=path44.join(projectRoot,MIGRATION_DIR2,"manifest.json");if(!fs42.existsSync(manifestPath))throw new MigrateCommandError("MIGRATION_MANIFEST_MISSING","No migration manifest found.",{hint:"Run `fimo migrate init <url>` first."});return JSON.parse(fs42.readFileSync(manifestPath,"utf8"))}function readCanonicalMigrationManifest(projectRoot){let manifestPath=path44.join(projectRoot,CANONICAL_MIGRATION_DIR,"manifest.json");if(!fs42.existsSync(manifestPath))throw new MigrateCommandError("MIGRATION_MANIFEST_MISSING","No migration manifest found.",{hint:`Run \`fimo migrate init <url>\` for a URL migration, or write the canonical ledger at ${toPosix2(CANONICAL_MIGRATION_DIR)}/manifest.json following the fimo-migration skill (\`fimo skills get fimo-migration\`) for a source-backed one.`});return JSON.parse(fs42.readFileSync(manifestPath,"utf8"))}function renderCanonicalManifestSummary(projectRoot,manifest){let count=__name(items=>items?.length??0,"count"),lines=[`Ledger: ${path44.join(projectRoot,CANONICAL_MIGRATION_DIR,"manifest.json")}`,`Mode: ${manifest.source?.mode??"unknown"}`,`Platform: ${manifest.source?.platform??"unknown"}`];return manifest.source?.publicUrl&&lines.push(`Source URL: ${manifest.source.publicUrl}`),manifest.source?.rootPath&&lines.push(`Source root: ${manifest.source.rootPath}`),lines.push(`Routes: ${count(manifest.routes)}`,`Content types: ${count(manifest.contentTypes)}`,`Entry batches: ${count(manifest.entries)}`,`Media: ${count(manifest.media)}`,`Forms: ${count(manifest.forms)}`,`Unresolved: ${count(manifest.unresolved)}`,`QA status: ${manifest.qa?.status??"not-run"}`),lines.join(`
|
|
1152
1152
|
`)}function loadProjectMetadata(projectRoot){let settings=loadProjectSettings(projectRoot);return{root:projectRoot,projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl}}function parseMaxPages(value,fallback=DEFAULT_MAX_PAGES){let parsed=Number.parseInt(value??`${fallback}`,10);return!Number.isFinite(parsed)||parsed<1?fallback:Math.min(parsed,30)}function parseMaxAssets(value,fallback=DEFAULT_MAX_ASSETS){let parsed=Number.parseInt(value??`${fallback}`,10);return!Number.isFinite(parsed)||parsed<0?fallback:Math.min(parsed,200)}async function buildMigrationArtifacts(args){let{project,sourceUrl,maxPages,maxAssets}=args,migrationRoot=path44.join(project.root,MIGRATION_DIR2),pagesRoot=path44.join(migrationRoot,SOURCE_PAGES_DIR),extractedRoot=path44.join(migrationRoot,EXTRACTED_DIR),mediaRoot=path44.join(migrationRoot,MEDIA_DIR);fs42.rmSync(migrationRoot,{recursive:!0,force:!0}),fs42.mkdirSync(pagesRoot,{recursive:!0}),fs42.mkdirSync(extractedRoot,{recursive:!0}),fs42.mkdirSync(mediaRoot,{recursive:!0});let crawl=await crawlSite({sourceUrl,maxPages,pagesRoot}),platform4=detectPlatformFromHtml(crawl.pages.map(page=>page.html).join(`
|
|
1153
1153
|
`),sourceUrl),designTokens=extractDesignTokens(crawl.pages.map(page=>page.html)),forms3=dedupeForms(crawl.pages.flatMap(page=>page.forms)),pages2=crawl.pages.map(page=>{let artifactPath=toPosix2(path44.relative(project.root,path44.join(pagesRoot,routeToFileName(page.route))));return{route:page.route,url:page.url,title:page.title,kind:page.kind,seo:{title:page.title,description:page.description},headings:page.headings,paragraphs:page.paragraphs,sections:page.sections,forms:page.forms,images:page.images,imageCount:page.imageUrls.length,artifacts:{html:artifactPath,screenshots:page.screenshots},confidence:page.confidence}}),collections=deriveCollections(pages2),allStylesheets=unique2(crawl.pages.flatMap(page=>page.stylesheetUrls)),allScripts=unique2(crawl.pages.flatMap(page=>page.scriptUrls)),allImages=unique2(crawl.pages.flatMap(page=>[...page.imageUrls,...page.backgroundImageUrls])),mediaAssets=args.downloadMedia?await downloadMediaAssets({urls:allImages,projectRoot:project.root,mediaRoot,maxAssets}):[],unresolved=deriveUnresolved({platform:platform4,pagesFetched:pages2.length,maxPages,forms:forms3,failures:crawl.failures,scriptUrls:allScripts}),recommendation=buildRecommendation({platform:platform4,unresolved,forms:forms3,collections}),manifest={version:1,source:{url:sourceUrl,platform:platform4,fetchedAt:new Date().toISOString()},project:{...project,migrationDir:toPosix2(MIGRATION_DIR2)},design:{tokens:designTokens,notes:buildDesignNotes(designTokens,platform4)},pages:pages2,collections,forms:forms3,assets:{images:allImages.length,stylesheets:allStylesheets.length,scripts:allScripts.length,downloaded:mediaAssets.filter(asset=>asset.status==="downloaded").length,failed:mediaAssets.filter(asset=>asset.status==="failed").length,manifest:mediaAssets.length>0?toPosix2(path44.relative(project.root,path44.join(mediaRoot,"map.json"))):void 0,externalHosts:unique2([...allImages,...allStylesheets,...allScripts].map(value=>safeHostname(value)).filter(value=>!!value))},crawl:{engine:crawl.engine,maxPages,pagesFetched:pages2.length,failures:crawl.failures},nextActions:buildNextActions({hasMedia:mediaAssets.some(asset=>asset.status==="downloaded"),hasCollections:collections.length>0,hasForms:forms3.length>0}),unresolved,recommendation};return fs42.writeFileSync(path44.join(migrationRoot,"manifest.json"),JSON.stringify(manifest,null,2)+`
|
|
@@ -1161,7 +1161,7 @@ ${fontImport}@import 'tailwindcss';
|
|
|
1161
1161
|
${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("cdn.prod.website-files.com")||haystack.includes("data-wf-")?"webflow":haystack.includes("framer")||haystack.includes("framerusercontent.com")?"framer":haystack.includes("squarespace")||haystack.includes("static1.squarespace.com")?"squarespace":haystack.includes("wix")||haystack.includes("wixstatic.com")||haystack.includes("parastorage.com")?"wix":haystack.includes("carrd")||haystack.includes("carrd.co")?"carrd":"unknown"}function extractDesignTokens(htmlDocs){let colors=topMatches(htmlDocs.flatMap(html3=>html3.match(/#[0-9a-fA-F]{3,8}\b|rgba?\([^)]+\)/g)??[]),12),radii=topMatches(htmlDocs.flatMap(html3=>html3.match(/\b\d+(?:\.\d+)?px\b/g)??[]),40).filter(value=>/^(?:4|6|8|10|12|14|16|20|24|32|40|48|56|64|72|80)px$/.test(value)),spacing=radii.filter(value=>/^(?:4|8|12|16|20|24|28|32|40|48|56|64|72|80|96|120)px$/.test(value)),fontMatches=htmlDocs.flatMap(html3=>{let direct=[...html3.matchAll(/font-family\s*:\s*([^;}"']+)/gi)].map(match=>cleanText2(match[1]??"")),googleFonts=[...html3.matchAll(/family=([^:&"']+)/gi)].map(match=>decodeURIComponent(match[1]??"").replace(/\+/g," "));return[...direct,...googleFonts].map(value=>value.split(",")[0]?.replace(/['"]/g,"").trim()??"").filter(Boolean)}),topFonts=topMatches(fontMatches,6).map((family,index2)=>({role:index2===0?"heading":index2===1?"body":"supporting",family}));return{colors,fonts:topFonts,radius:radii.slice(0,8),spacing:spacing.slice(0,8)}}function buildDesignNotes(tokens,platform4){let notes=[];return tokens.colors.length>0&¬es.push(`Detected ${tokens.colors.length} recurring color tokens.`),tokens.fonts.length>0&¬es.push(`Detected font families: ${tokens.fonts.map(font=>font.family).join(", ")}.`),platform4!=="unknown"&¬es.push(`Source platform appears to be ${platform4}.`),notes}async function downloadMediaAssets(args){let selected=args.urls.slice(0,args.maxAssets),assets3=[],originalsRoot=path44.join(args.mediaRoot,"originals");fs42.mkdirSync(originalsRoot,{recursive:!0});for(let sourceUrl of selected){let fileName=mediaFileName(sourceUrl,assets3.length+1),localPath=path44.join(originalsRoot,fileName);try{let response=await fetch(sourceUrl,{headers:{"user-agent":USER_AGENT,accept:"image/avif,image/webp,image/png,image/jpeg,image/svg+xml,image/*,*/*;q=0.8"}});if(!response.ok)throw new Error(`HTTP ${response.status}`);let contentType=response.headers.get("content-type");if(contentType&&!contentType.startsWith("image/"))throw new Error(`Unsupported content type ${contentType}`);let buffer=Buffer.from(await response.arrayBuffer());fs42.writeFileSync(localPath,buffer),assets3.push({sourceUrl,fileName,localPath:toPosix2(path44.relative(args.projectRoot,localPath)),contentType,bytes:buffer.byteLength,status:"downloaded"})}catch(error){assets3.push({sourceUrl,fileName,localPath:null,contentType:null,bytes:null,status:"failed",error:error instanceof Error?error.message:String(error)})}}return assets3}function mediaFileName(sourceUrl,index2){let url=new URL(sourceUrl),original=path44.basename(url.pathname).replace(/[^a-zA-Z0-9._-]/g,"-"),ext=path44.extname(original)||".bin",stem=path44.basename(original,ext)||"asset";return`${String(index2).padStart(3,"0")}-${slugify2(stem).slice(0,48)||"asset"}${ext}`}function buildNextActions(args){let actions=["Read `.fimo/migrations/current/refine/agent-prompt.md` and perform the source-faithful rebuild pass."];return(args.hasMedia||args.hasCollections||args.hasForms)&&actions.push("Import the generated content into Fimo (required): run `fimo migrate import` to print the exact `fimo assets upload` / `fimo schemas push` / `fimo entries create` / `fimo forms push` commands, then run them. Generated JSON is not imported content."),args.hasMedia&&actions.push("Use `.fimo/migrations/current/media/map.json` to replace source image URLs with uploaded Fimo media assets."),actions}function deriveCollections(pages2){let groups=new Map;for(let page of pages2){let segments=stripLeadingLocale(page.route.split("/").filter(Boolean));if(segments.length<2)continue;let[prefix]=segments;if(!prefix||isLocaleSegment(prefix)||COLLECTION_ROUTE_BLACKLIST.has(prefix))continue;let key=prefix.toLowerCase();groups.set(key,[...groups.get(key)??[],page])}return[...groups.entries()].filter(([,group])=>group.length>=2).map(([prefix,group])=>({name:`${prefix}-items`,sourceRoutes:group.map(page=>page.route).sort(),suggestedSchema:toPascalCase(singularize(prefix)),fields:deriveCollectionFields(group),confidence:group.length>=3?.84:.72})).sort((a,b)=>b.sourceRoutes.length-a.sourceRoutes.length)}function deriveCollectionFields(group){let fields=new Set(["title","slug","body"]);return group.some(page=>page.imageCount>0)&&fields.add("coverImage"),group.some(page=>/date|time|news|blog|journal/i.test(page.route))&&fields.add("publishedAt"),group.some(page=>page.seo.description)&&fields.add("excerpt"),[...fields]}function dedupeForms(forms3){let seen=new Set,results=[];for(let form of forms3){let key=`${form.route}:${form.name}:${form.fields.map(field=>`${field.name}:${field.kind}`).join("|")}`;seen.has(key)||(seen.add(key),results.push(form))}return results}function deriveUnresolved(args){let issues=[];return args.forms.length>0&&issues.push("Builder form backends do not migrate directly. Replace them with Fimo forms."),args.platform==="wix"&&issues.push("Wix sites are often heavily client-rendered and may need manual review before large-scale rebuilding."),args.pagesFetched>=args.maxPages&&issues.push(`The crawler hit its ${args.maxPages}-page limit. Re-run with --max-pages if the site is larger.`),args.failures.length>0&&issues.push(`Some routes failed to crawl (${args.failures.length}). Inspect crawl.failures in the manifest.`),args.scriptUrls.some(url=>/webpack|chunk|bundle|framer|wix|webflow/i.test(url))&&issues.push("The source site appears to rely on builder runtime scripts. Rebuild the behavior rather than preserving raw runtime code."),issues}function buildRecommendation(args){return args.platform==="wix"?{mode:"manual-review-first",reason:"Wix migrations are often app-like and runtime-heavy."}:args.unresolved.length>=3&&args.collections.length===0&&args.forms.length>1?{mode:"manual-review-first",reason:"The crawl surfaced several unsupported behaviors with limited structural confidence."}:{mode:"rebuild-in-fimo",reason:"The site looks like a normal marketing or light CMS migration that should be rebuilt with Fimo primitives."}}function buildMigrationBrief(manifest){return["# Migration Brief","",`- Source: ${manifest.source.url}`,`- Platform: ${manifest.source.platform}`,`- Fetched: ${manifest.source.fetchedAt}`,`- Recommendation: ${manifest.recommendation.mode} - ${manifest.recommendation.reason}`,"","## Pages",...manifest.pages.map(page=>`- \`${page.route}\` - ${page.title} (${page.kind})`),"","## Collections",...manifest.collections.length>0?manifest.collections.map(collection=>`- \`${collection.suggestedSchema}\` from ${collection.sourceRoutes.length} source routes`):["- None inferred confidently"],"","## Forms",...manifest.forms.length>0?manifest.forms.map(form=>`- \`${form.name}\` on \`${form.route}\` with fields: ${form.fields.map(field=>field.name).join(", ")}`):["- No forms detected"],"","## Unresolved",...manifest.unresolved.length>0?manifest.unresolved.map(item=>`- ${item}`):["- No major blockers detected"],"","## Next steps",...manifest.nextActions&&manifest.nextActions.length>0?manifest.nextActions.map(action=>`- ${action}`):["- Read `manifest.json` for the structured summary.","- Read the project `fimo` skill references before major code generation.","- Rebuild pages with Fimo primitives rather than preserving builder runtime code."]].join(`
|
|
1162
1162
|
`)}function renderManifestSummary(manifest){let lines=[`Source: ${manifest.source.url}`,`Platform: ${manifest.source.platform}`,`Pages: ${manifest.pages.length}`,`Collections: ${manifest.collections.length}`,`Forms: ${manifest.forms.length}`,`Crawl engine: ${manifest.crawl.engine??"fetch"}`];return manifest.assets.downloaded!==void 0&&lines.push(`Media: ${manifest.assets.downloaded}/${manifest.assets.images} downloaded`),lines.push(`Recommendation: ${manifest.recommendation.mode}`,`Artifacts: ${path44.join(manifest.project.root,manifest.project.migrationDir)}`),manifest.unresolved.length>0&&lines.push("","Unresolved",...manifest.unresolved.map(issue=>`- ${issue}`)),lines.join(`
|
|
1163
1163
|
`)}function renderApplyResult(projectRoot,result){return[`Project: ${projectRoot}`,`Pages written: ${result.pagesWritten}`,`Schemas: ${result.schemasWritten}`,`Forms: ${result.formsWritten}`,`Files written: ${result.written.length}`,`Translations: +${result.translations.created} ~${result.translations.updated} -${result.translations.deleted}`,`Codegen: schemas +${result.codegen.schemas.created}/~${result.codegen.schemas.updated}, forms +${result.codegen.forms.created}/~${result.codegen.forms.updated}`].join(`
|
|
1164
|
-
`)}function normalizeSourceUrl(value){let raw=value.trim();return/^https?:\/\//i.test(raw)?raw:`https://${raw}`}function shouldVisitLink(href,siteOrigin){try{let url=new URL(href);if(url.origin!==siteOrigin)return!1;url.hash&&(url.hash=""),url.search&&(url.search="");let route=normalizeRoutePath2(url.pathname);return!(route.startsWith("/cdn-cgi/")||/\.[a-z0-9]{2,5}$/i.test(route)&&!route.endsWith(".html"))}catch{return!1}}function normalizeDiscoveredUrl(href){let url=new URL(href);return url.hash="",url.search="",url.pathname=normalizeRoutePath2(url.pathname),url.toString()}function absolutizeUrl2(value,base){if(!value)return null;let trimmed=value.trim();if(!trimmed||trimmed.startsWith("#")||trimmed.startsWith("mailto:")||trimmed.startsWith("tel:"))return null;try{return new URL(trimmed,base).toString()}catch{return null}}function extractImageCandidates($2,element,pageUrl){let node=$2(element);return unique2([node.attr("src"),node.attr("data-src"),...parseSrcSet(node.attr("srcset")),...parseSrcSet(node.attr("data-srcset"))].map(value=>absolutizeUrl2(value,pageUrl)).filter(value=>!!value).filter(value=>/^https?:\/\//i.test(value)))}function parseSrcSet(value){return value?value.split(",").map(candidate=>candidate.trim().split(/\s+/)[0]).filter(candidate=>!!candidate):[]}function extractBackgroundImages(style,pageUrl){return[...style.matchAll(/url\((['"]?)(.*?)\1\)/gi)].map(match=>absolutizeUrl2(match[2],pageUrl)).filter(value=>!!value).filter(value=>/^https?:\/\//i.test(value))}function uniqueImageObjects2(images){let seen=new Set,results=[];for(let image of images)seen.has(image.src)||(seen.add(image.src),results.push(image));return results}function normalizeRoutePath2(pathname){let route=pathname.trim();return route?(route=route.replace(/index\.html?$/i,""),route=route.replace(/\.html?$/i,""),route=route.replace(/\/{2,}/g,"/"),route.startsWith("/")||(route=`/${route}`),route.length>1&&route.endsWith("/")&&(route=route.slice(0,-1)),route||"/"):"/"}function routeToFileName(route){return route==="/"?"index.html":`${route.replace(/^\//,"").replace(/\//g,"__")||"page"}.html`}function classifyPageKind(route,title){let lower=`${route} ${title}`.toLowerCase();return LEGAL_ROUTES.has(route)?"legal":lower.includes("contact")?"contact":/\/(blog|news|journal|articles)\//.test(route)?"blog-post":/\/(blog|news|journal|articles)$/.test(route)||/\bblog\b|\bnews\b|\bjournal\b/.test(lower)?"blog-index":"marketing"}function computePageConfidence(args){let score=.58;return args.title.length>0&&(score+=.12),args.headings.length>0&&(score+=.12),args.imageUrls.length>0&&(score+=.06),args.forms.length>0&&(score+=.06),args.route!=="/"&&(score+=.04),Math.min(.96,Number(score.toFixed(2)))}function guessSectionKind(label,index2){let lower=label.toLowerCase();return index2===0?"hero":lower.includes("feature")||lower.includes("service")?"feature-grid":lower.includes("testimonial")||lower.includes("review")?"testimonials":lower.includes("faq")?"faq":lower.includes("pricing")?"pricing":lower.includes("contact")?"contact":lower.includes("cta")||lower.includes("start")?"cta":"content-section"}function cleanText2(value){return value.replace(/\s+/g," ").trim()}function titleizeFieldName(value){return value.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}function fallbackTitleFromRoute(route){return route==="/"?"Home":route.split("/").filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}function safeHostname(value){try{return new URL(value).hostname}catch{return null}}function unique2(values){return[...new Set(values)]}function topMatches(values,limit){let counts=new Map;for(let value of values){let normalized=cleanText2(value);normalized&&counts.set(normalized,(counts.get(normalized)??0)+1)}return[...counts.entries()].sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0])).slice(0,limit).map(([value])=>value)}function slugify2(value){return value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function singularize(value){return value.endsWith("ies")?`${value.slice(0,-3)}y`:value.endsWith("s")&&!value.endsWith("ss")?value.slice(0,-1):value}function isLocaleSegment(segment){let canonical;try{canonical=Intl.getCanonicalLocales(segment.replace(/_/g,"-"))}catch{return!1}if(canonical.length===0)return!1;let language=new Intl.Locale(canonical[0]).language;return language.length<2||language.length>3?!1:!!localeDisplayNames.of(language)}function stripLeadingLocale(segments){let start=0;for(;start<segments.length&&isLocaleSegment(segments[start]);)start+=1;return segments.slice(start)}function toPascalCase(value){return value.split(/[^a-zA-Z0-9]/).filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join("")}function toPosix2(value){return value.split(path44.sep).join("/")}var DEFAULT_MAX_PAGES,DEFAULT_MAX_ASSETS,MIGRATION_DIR2,CANONICAL_MIGRATION_DIR,CLI_ROOT3,MIGRATION_SKILL_SCRIPTS_DIR,SOURCE_PAGES_DIR,EXTRACTED_DIR,MEDIA_DIR,USER_AGENT,LEGAL_ROUTES,COLLECTION_ROUTE_BLACKLIST,MigrateCommandError,MigrateCancelled,localeDisplayNames,init_migrate=__esm({"src/cli/commands/migrate.ts"(){init_dist();init_slim();init_auth();init_config();init_project();init_init();init_migrate_apply();DEFAULT_MAX_PAGES=12,DEFAULT_MAX_ASSETS=40,MIGRATION_DIR2=path44.join(".fimo","migrations","current"),CANONICAL_MIGRATION_DIR=path44.join(".fimo","migration"),CLI_ROOT3=path44.resolve(path44.dirname(fileURLToPath6(import.meta.url)),"..","..",".."),MIGRATION_SKILL_SCRIPTS_DIR=path44.join(CLI_ROOT3,"assets","skills","fimo-migration","scripts"),SOURCE_PAGES_DIR=path44.join("source","pages"),EXTRACTED_DIR="extracted",MEDIA_DIR="media",USER_AGENT="fimo-cli migrate/0.1",LEGAL_ROUTES=new Set(["/privacy","/privacy-policy","/terms","/terms-of-service","/cookies"]),COLLECTION_ROUTE_BLACKLIST=new Set(["about","careers","contact","legal","privacy","terms","pricing","features","services","work"]),MigrateCommandError=class extends Error{static{__name(this,"MigrateCommandError")}code;hint;constructor(code2,message,opts={}){super(message),this.code=code2,opts.hint!==void 0&&(this.hint=opts.hint)}},MigrateCancelled=class extends Error{static{__name(this,"MigrateCancelled")}constructor(message="Cancelled."){super(message)}};__name(emitMigrateError,"emitMigrateError");__name(crawlMigrationArtifacts,"crawlMigrationArtifacts");__name(isMigrationSourceUrl,"isMigrationSourceUrl");__name(migrateInitCommand,"migrateInitCommand");__name(migratePullCommand,"migratePullCommand");__name(migrateRunCommand,"migrateRunCommand");__name(wrapMigrateError,"wrapMigrateError");__name(migrateInspectCommand,"migrateInspectCommand");__name(migrateApplyCommand,"migrateApplyCommand");__name(migrateImportCommand,"migrateImportCommand");__name(migrateManifestCommand,"migrateManifestCommand");__name(migrateReportCommand,"migrateReportCommand");__name(runBundledMigrationScript,"runBundledMigrationScript");__name(readStringOption,"readStringOption");__name(readDownloadedMedia,"readDownloadedMedia");__name(ensureMigrationProject,"ensureMigrationProject");__name(runSourceBackedInit,"runSourceBackedInit");__name(requireMigrateAuth,"requireMigrateAuth");__name(buildSourceInitReceipt,"buildSourceInitReceipt");__name(readTargetFramework,"readTargetFramework");__name(assertRequestedFramework,"assertRequestedFramework");__name(renderSourceInitReceipt,"renderSourceInitReceipt");__name(requireProjectRoot,"requireProjectRoot");__name(readMigrationManifest,"readMigrationManifest");__name(readCanonicalMigrationManifest,"readCanonicalMigrationManifest");__name(renderCanonicalManifestSummary,"renderCanonicalManifestSummary");__name(loadProjectMetadata,"loadProjectMetadata");__name(parseMaxPages,"parseMaxPages");__name(parseMaxAssets,"parseMaxAssets");__name(buildMigrationArtifacts,"buildMigrationArtifacts");__name(crawlSite,"crawlSite");__name(crawlSiteWithFetch,"crawlSiteWithFetch");__name(analyzePage,"analyzePage");__name(extractForms,"extractForms");__name(detectPlatformFromHtml,"detectPlatformFromHtml");__name(extractDesignTokens,"extractDesignTokens");__name(buildDesignNotes,"buildDesignNotes");__name(downloadMediaAssets,"downloadMediaAssets");__name(mediaFileName,"mediaFileName");__name(buildNextActions,"buildNextActions");__name(deriveCollections,"deriveCollections");__name(deriveCollectionFields,"deriveCollectionFields");__name(dedupeForms,"dedupeForms");__name(deriveUnresolved,"deriveUnresolved");__name(buildRecommendation,"buildRecommendation");__name(buildMigrationBrief,"buildMigrationBrief");__name(renderManifestSummary,"renderManifestSummary");__name(renderApplyResult,"renderApplyResult");__name(normalizeSourceUrl,"normalizeSourceUrl");__name(shouldVisitLink,"shouldVisitLink");__name(normalizeDiscoveredUrl,"normalizeDiscoveredUrl");__name(absolutizeUrl2,"absolutizeUrl");__name(extractImageCandidates,"extractImageCandidates");__name(parseSrcSet,"parseSrcSet");__name(extractBackgroundImages,"extractBackgroundImages");__name(uniqueImageObjects2,"uniqueImageObjects");__name(normalizeRoutePath2,"normalizeRoutePath");__name(routeToFileName,"routeToFileName");__name(classifyPageKind,"classifyPageKind");__name(computePageConfidence,"computePageConfidence");__name(guessSectionKind,"guessSectionKind");__name(cleanText2,"cleanText");__name(titleizeFieldName,"titleizeFieldName");__name(fallbackTitleFromRoute,"fallbackTitleFromRoute");__name(safeHostname,"safeHostname");__name(unique2,"unique");__name(topMatches,"topMatches");__name(slugify2,"slugify");__name(singularize,"singularize");localeDisplayNames=new Intl.DisplayNames(["en"],{type:"language",fallback:"none"});__name(isLocaleSegment,"isLocaleSegment");__name(stripLeadingLocale,"stripLeadingLocale");__name(toPascalCase,"toPascalCase");__name(toPosix2,"toPosix")}});var migrate_refine_exports={};__export(migrate_refine_exports,{migrateRefineCommand:()=>migrateRefineCommand,prepareMigrationRefineArtifacts:()=>prepareMigrationRefineArtifacts});import fs43 from"node:fs";import path45 from"node:path";function migrateRefineCommand(options){let command="migrate refine";try{let projectRoot=requireProjectRoot(options.cwd),manifest=readMigrationManifest(projectRoot),sp=spinner("Preparing migration refinement handoff"),result;try{result=prepareMigrationRefineArtifacts({cwd:projectRoot,manifest,focusRoute:options.route})}catch(error){throw sp.fail("Migration refine failed"),error}sp.succeed("Migration refinement pack written"),ui.result({command,data:result,render:__name(()=>[`Project: ${projectRoot}`,`Pages prepared: ${result.pagesPrepared}`,`Focus route: ${result.focusRoute??"all routes"}`,`Prompt: ${path45.join(projectRoot,result.promptPath)}`,`Summary: ${path45.join(projectRoot,result.summaryPath)}`,`Page briefs: ${result.pageBriefs.length}`].join(`
|
|
1164
|
+
`)}function normalizeSourceUrl(value){let raw=value.trim();return/^https?:\/\//i.test(raw)?raw:`https://${raw}`}function shouldVisitLink(href,siteOrigin){try{let url=new URL(href);if(url.origin!==siteOrigin)return!1;url.hash&&(url.hash=""),url.search&&(url.search="");let route=normalizeRoutePath2(url.pathname);return!(route.startsWith("/cdn-cgi/")||/\.[a-z0-9]{2,5}$/i.test(route)&&!route.endsWith(".html"))}catch{return!1}}function normalizeDiscoveredUrl(href){let url=new URL(href);return url.hash="",url.search="",url.pathname=normalizeRoutePath2(url.pathname),url.toString()}function absolutizeUrl2(value,base){if(!value)return null;let trimmed=value.trim();if(!trimmed||trimmed.startsWith("#")||trimmed.startsWith("mailto:")||trimmed.startsWith("tel:"))return null;try{return new URL(trimmed,base).toString()}catch{return null}}function extractImageCandidates($2,element,pageUrl){let node=$2(element);return unique2([node.attr("src"),node.attr("data-src"),...parseSrcSet(node.attr("srcset")),...parseSrcSet(node.attr("data-srcset"))].map(value=>absolutizeUrl2(value,pageUrl)).filter(value=>!!value).filter(value=>/^https?:\/\//i.test(value)))}function parseSrcSet(value){return value?value.split(",").map(candidate=>candidate.trim().split(/\s+/)[0]).filter(candidate=>!!candidate):[]}function extractBackgroundImages(style,pageUrl){return[...style.matchAll(/url\((['"]?)(.*?)\1\)/gi)].map(match=>absolutizeUrl2(match[2],pageUrl)).filter(value=>!!value).filter(value=>/^https?:\/\//i.test(value))}function uniqueImageObjects2(images){let seen=new Set,results=[];for(let image of images)seen.has(image.src)||(seen.add(image.src),results.push(image));return results}function normalizeRoutePath2(pathname){let route=pathname.trim();return route?(route=route.replace(/index\.html?$/i,""),route=route.replace(/\.html?$/i,""),route=route.replace(/\/{2,}/g,"/"),route.startsWith("/")||(route=`/${route}`),route.length>1&&route.endsWith("/")&&(route=route.slice(0,-1)),route||"/"):"/"}function routeToFileName(route){return route==="/"?"index.html":`${route.replace(/^\//,"").replace(/\//g,"__")||"page"}.html`}function classifyPageKind(route,title){let lower=`${route} ${title}`.toLowerCase();return LEGAL_ROUTES.has(route)?"legal":lower.includes("contact")?"contact":/\/(blog|news|journal|articles)\//.test(route)?"blog-post":/\/(blog|news|journal|articles)$/.test(route)||/\bblog\b|\bnews\b|\bjournal\b/.test(lower)?"blog-index":"marketing"}function computePageConfidence(args){let score=.58;return args.title.length>0&&(score+=.12),args.headings.length>0&&(score+=.12),args.imageUrls.length>0&&(score+=.06),args.forms.length>0&&(score+=.06),args.route!=="/"&&(score+=.04),Math.min(.96,Number(score.toFixed(2)))}function guessSectionKind(label,index2){let lower=label.toLowerCase();return index2===0?"hero":lower.includes("feature")||lower.includes("service")?"feature-grid":lower.includes("testimonial")||lower.includes("review")?"testimonials":lower.includes("faq")?"faq":lower.includes("pricing")?"pricing":lower.includes("contact")?"contact":lower.includes("cta")||lower.includes("start")?"cta":"content-section"}function cleanText2(value){return value.replace(/\s+/g," ").trim()}function titleizeFieldName(value){return value.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}function fallbackTitleFromRoute(route){return route==="/"?"Home":route.split("/").filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}function safeHostname(value){try{return new URL(value).hostname}catch{return null}}function unique2(values){return[...new Set(values)]}function topMatches(values,limit){let counts=new Map;for(let value of values){let normalized=cleanText2(value);normalized&&counts.set(normalized,(counts.get(normalized)??0)+1)}return[...counts.entries()].sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0])).slice(0,limit).map(([value])=>value)}function slugify2(value){return value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function singularize(value){return value.endsWith("ies")?`${value.slice(0,-3)}y`:value.endsWith("s")&&!value.endsWith("ss")?value.slice(0,-1):value}function isLocaleSegment(segment){let canonical;try{canonical=Intl.getCanonicalLocales(segment.replace(/_/g,"-"))}catch{return!1}if(canonical.length===0)return!1;let language=new Intl.Locale(canonical[0]).language;return language.length<2||language.length>3?!1:!!localeDisplayNames.of(language)}function stripLeadingLocale(segments){let start=0;for(;start<segments.length&&isLocaleSegment(segments[start]);)start+=1;return segments.slice(start)}function toPascalCase(value){return value.split(/[^a-zA-Z0-9]/).filter(Boolean).map(part=>part.charAt(0).toUpperCase()+part.slice(1)).join("")}function toPosix2(value){return value.split(path44.sep).join("/")}var DEFAULT_MAX_PAGES,DEFAULT_MAX_ASSETS,MIGRATION_DIR2,CANONICAL_MIGRATION_DIR,CLI_ROOT3,MIGRATION_SKILL_SCRIPTS_DIR,SOURCE_PAGES_DIR,EXTRACTED_DIR,MEDIA_DIR,USER_AGENT,LEGAL_ROUTES,COLLECTION_ROUTE_BLACKLIST,MigrateCommandError,MigrateCancelled,localeDisplayNames,init_migrate=__esm({"src/cli/commands/migrate.ts"(){init_esm();init_dist();init_slim();init_api();init_auth();init_config();init_project();init_init();init_migrate_apply();DEFAULT_MAX_PAGES=12,DEFAULT_MAX_ASSETS=40,MIGRATION_DIR2=path44.join(".fimo","migrations","current"),CANONICAL_MIGRATION_DIR=path44.join(".fimo","migration"),CLI_ROOT3=path44.resolve(path44.dirname(fileURLToPath6(import.meta.url)),"..","..",".."),MIGRATION_SKILL_SCRIPTS_DIR=path44.join(CLI_ROOT3,"assets","skills","fimo-migration","scripts"),SOURCE_PAGES_DIR=path44.join("source","pages"),EXTRACTED_DIR="extracted",MEDIA_DIR="media",USER_AGENT="fimo-cli migrate/0.1",LEGAL_ROUTES=new Set(["/privacy","/privacy-policy","/terms","/terms-of-service","/cookies"]),COLLECTION_ROUTE_BLACKLIST=new Set(["about","careers","contact","legal","privacy","terms","pricing","features","services","work"]),MigrateCommandError=class extends Error{static{__name(this,"MigrateCommandError")}code;hint;constructor(code2,message,opts={}){super(message),this.code=code2,opts.hint!==void 0&&(this.hint=opts.hint)}},MigrateCancelled=class extends Error{static{__name(this,"MigrateCancelled")}constructor(message="Cancelled."){super(message)}};__name(emitMigrateError,"emitMigrateError");__name(crawlMigrationArtifacts,"crawlMigrationArtifacts");__name(isMigrationSourceUrl,"isMigrationSourceUrl");__name(migrateInitCommand,"migrateInitCommand");__name(migratePullCommand,"migratePullCommand");__name(migrateRunCommand,"migrateRunCommand");__name(wrapMigrateError,"wrapMigrateError");__name(migrateInspectCommand,"migrateInspectCommand");__name(migrateApplyCommand,"migrateApplyCommand");__name(migrateImportCommand,"migrateImportCommand");__name(migrateManifestCommand,"migrateManifestCommand");__name(migrateReportCommand,"migrateReportCommand");__name(parseSourcePlatform,"parseSourcePlatform");__name(crawledSourcePlatform,"crawledSourcePlatform");__name(reportMigration,"reportMigration");__name(reportMigrationFailure,"reportMigrationFailure");__name(runBundledMigrationScript,"runBundledMigrationScript");__name(readStringOption,"readStringOption");__name(readDownloadedMedia,"readDownloadedMedia");__name(ensureMigrationProject,"ensureMigrationProject");__name(runSourceBackedInit,"runSourceBackedInit");__name(requireMigrateAuth,"requireMigrateAuth");__name(buildSourceInitReceipt,"buildSourceInitReceipt");__name(readTargetFramework,"readTargetFramework");__name(assertRequestedFramework,"assertRequestedFramework");__name(renderSourceInitReceipt,"renderSourceInitReceipt");__name(requireProjectRoot,"requireProjectRoot");__name(readMigrationManifest,"readMigrationManifest");__name(readCanonicalMigrationManifest,"readCanonicalMigrationManifest");__name(renderCanonicalManifestSummary,"renderCanonicalManifestSummary");__name(loadProjectMetadata,"loadProjectMetadata");__name(parseMaxPages,"parseMaxPages");__name(parseMaxAssets,"parseMaxAssets");__name(buildMigrationArtifacts,"buildMigrationArtifacts");__name(crawlSite,"crawlSite");__name(crawlSiteWithFetch,"crawlSiteWithFetch");__name(analyzePage,"analyzePage");__name(extractForms,"extractForms");__name(detectPlatformFromHtml,"detectPlatformFromHtml");__name(extractDesignTokens,"extractDesignTokens");__name(buildDesignNotes,"buildDesignNotes");__name(downloadMediaAssets,"downloadMediaAssets");__name(mediaFileName,"mediaFileName");__name(buildNextActions,"buildNextActions");__name(deriveCollections,"deriveCollections");__name(deriveCollectionFields,"deriveCollectionFields");__name(dedupeForms,"dedupeForms");__name(deriveUnresolved,"deriveUnresolved");__name(buildRecommendation,"buildRecommendation");__name(buildMigrationBrief,"buildMigrationBrief");__name(renderManifestSummary,"renderManifestSummary");__name(renderApplyResult,"renderApplyResult");__name(normalizeSourceUrl,"normalizeSourceUrl");__name(shouldVisitLink,"shouldVisitLink");__name(normalizeDiscoveredUrl,"normalizeDiscoveredUrl");__name(absolutizeUrl2,"absolutizeUrl");__name(extractImageCandidates,"extractImageCandidates");__name(parseSrcSet,"parseSrcSet");__name(extractBackgroundImages,"extractBackgroundImages");__name(uniqueImageObjects2,"uniqueImageObjects");__name(normalizeRoutePath2,"normalizeRoutePath");__name(routeToFileName,"routeToFileName");__name(classifyPageKind,"classifyPageKind");__name(computePageConfidence,"computePageConfidence");__name(guessSectionKind,"guessSectionKind");__name(cleanText2,"cleanText");__name(titleizeFieldName,"titleizeFieldName");__name(fallbackTitleFromRoute,"fallbackTitleFromRoute");__name(safeHostname,"safeHostname");__name(unique2,"unique");__name(topMatches,"topMatches");__name(slugify2,"slugify");__name(singularize,"singularize");localeDisplayNames=new Intl.DisplayNames(["en"],{type:"language",fallback:"none"});__name(isLocaleSegment,"isLocaleSegment");__name(stripLeadingLocale,"stripLeadingLocale");__name(toPascalCase,"toPascalCase");__name(toPosix2,"toPosix")}});var migrate_refine_exports={};__export(migrate_refine_exports,{migrateRefineCommand:()=>migrateRefineCommand,prepareMigrationRefineArtifacts:()=>prepareMigrationRefineArtifacts});import fs43 from"node:fs";import path45 from"node:path";function migrateRefineCommand(options){let command="migrate refine";try{let projectRoot=requireProjectRoot(options.cwd),manifest=readMigrationManifest(projectRoot),sp=spinner("Preparing migration refinement handoff"),result;try{result=prepareMigrationRefineArtifacts({cwd:projectRoot,manifest,focusRoute:options.route})}catch(error){throw sp.fail("Migration refine failed"),error}sp.succeed("Migration refinement pack written"),ui.result({command,data:result,render:__name(()=>[`Project: ${projectRoot}`,`Pages prepared: ${result.pagesPrepared}`,`Focus route: ${result.focusRoute??"all routes"}`,`Prompt: ${path45.join(projectRoot,result.promptPath)}`,`Summary: ${path45.join(projectRoot,result.summaryPath)}`,`Page briefs: ${result.pageBriefs.length}`].join(`
|
|
1165
1165
|
`),"render"),hint:`Open ${path45.join(projectRoot,result.promptPath)} and paste it to your coding agent.`})}catch(error){emitMigrateError(command,error,"MIGRATION_REFINE_FAILED")}}function prepareMigrationRefineArtifacts(args){let{cwd,manifest,focusRoute}=args,pages2=selectPagesForRefine(manifest,focusRoute);if(pages2.length===0)throw new Error(focusRoute?`Route ${focusRoute} was not found in the migration manifest.`:"No pages available in the migration manifest.");let generatedArtifacts=readGeneratedArtifacts(cwd),refineRootAbs=path45.join(cwd,REFINE_ROOT),pageBriefsAbs=path45.join(cwd,PAGE_BRIEFS_DIR);fs43.rmSync(refineRootAbs,{recursive:!0,force:!0}),fs43.mkdirSync(pageBriefsAbs,{recursive:!0});let written=[],pageSummaries=[],mediaMap=readMediaMap(cwd,manifest);for(let page of pages2){let pageSummary=writePageBrief({cwd,manifest,page,generatedArtifacts,mediaMap,written});pageSummaries.push(pageSummary)}let summaryPath=path45.join(REFINE_ROOT,"summary.json"),promptPath=path45.join(REFINE_ROOT,"agent-prompt.md");return writeFile4(cwd,summaryPath,JSON.stringify({generatedAt:new Date().toISOString(),source:manifest.source,focusRoute:focusRoute??null,pages:pageSummaries,unresolved:manifest.unresolved},null,2)+`
|
|
1166
1166
|
`,written),writeFile4(cwd,promptPath,buildAgentPrompt(manifest,pageSummaries,focusRoute)+`
|
|
1167
1167
|
`,written),{written,pagesPrepared:pageSummaries.length,focusRoute:focusRoute??null,promptPath,summaryPath,pageBriefs:pageSummaries.map(page=>page.briefPath)}}function selectPagesForRefine(manifest,focusRoute){if(!focusRoute)return manifest.pages;let normalized=normalizeRoute(focusRoute);return manifest.pages.filter(page=>normalizeRoute(page.route)===normalized)}function writePageBrief(args){let{cwd,manifest,page,generatedArtifacts,mediaMap,written}=args,sourceHtmlPath=path45.join(cwd,page.artifacts.html),sourceHtml=fs43.existsSync(sourceHtmlPath)?fs43.readFileSync(sourceHtmlPath,"utf8"):"",outline=analyzeSourceHtml(sourceHtml,manifest.source.url),pageMedia=mediaMap.filter(asset=>outline.images.some(image=>normalizeUrlForMatch(image.src)===normalizeUrlForMatch(asset.sourceUrl))),targetModule=resolveGeneratedPageModule(cwd,page.route,generatedArtifacts),currentTemplate=detectCurrentTemplate(targetModule),briefPath=path45.join(PAGE_BRIEFS_DIR,`${routeToBriefFile(page.route)}.md`);return writeFile4(cwd,briefPath,buildPageBrief({page,manifest,sourceHtmlPath:page.artifacts.html,targetModule:targetModule?toPosix3(path45.relative(cwd,targetModule)):null,currentTemplate,outline,pageMedia})+`
|
|
@@ -1186,12 +1186,12 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
|
|
|
1186
1186
|
${target}: Fimo branch not created yet`}}function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve10({kind:"ok",value})},error=>{clearTimeout(t2),resolve10({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit(["status","--porcelain"],cwd)).split(`
|
|
1187
1187
|
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path53=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path53,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),api=new FimoApiClient().withBranch(ctx.branch),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(api,ctx.projectId,ctx.branch,cwd),serverPromise=withSoftTimeout(api.getBranchStatus(ctx.projectId,ctx.branch,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,checkout,serverResult]=await Promise.all([codePromise,checkoutPromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let server=serverResult.value,serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,checkout,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
|
|
1188
1188
|
|
|
1189
|
-
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs51 from"node:fs";import path52 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor,config){let value=Number(cursor??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page=await input.fetchPage(input.cursor);if(!input.allPages||page.nextCursor===null)return page;let items=[...page.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page.nextCursor!==null;){if(seen.has(page.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page.nextCursor),page=await input.fetchPage(page.nextCursor),items.push(...page.items)}return{...page,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z75}from"zod";var CapabilityTokenSchema=z75.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z75.array(CapabilityTokenSchema);import{z as z76}from"zod";var CronTriggerSchema=z76.object({type:z76.literal("schedule"),cron:z76.string().min(1,"cron expression required"),tz:z76.string().optional()}),ManualTriggerSchema2=z76.object({type:z76.literal("manual")}),WebhookTriggerSchema2=z76.object({type:z76.literal("webhook"),path:z76.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z76.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z76.object({name:z76.string().min(1),capability_grant:z76.enum(["inherit","explicit"]).optional(),explicit_grants:z76.array(z76.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z76.object({"sub-agents":z76.array(SubAgentRefSchema)}),RuntimeConfigSchema=z76.object({cloud:z76.boolean().optional(),dev:z76.boolean().optional(),long_running:z76.boolean().optional()}),DataSourceSchema=z76.enum(["main","prod"]),ConfigValueKeySchema=z76.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z76.preprocess(value=>typeof value=="string"?{key:value}:value,z76.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z76.boolean().default(!0),delivery:z76.literal("process_env").default("process_env")})),IntegrationKeySchema=z76.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z76.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z76.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z76.object({enabled:z76.boolean().default(!0),tools:z76.record(IntegrationToolKeySchema,z76.boolean()).optional()})),IntegrationPolicySchema=z76.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z76.object({version:z76.literal(1),description:z76.string().min(1).max(280).optional(),model:z76.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z76.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z76.array(DataSourceSchema).optional(),secrets:z76.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES,CAPABILITY_NAMESPACE_SELECTOR=/^([a-z][a-z0-9_]*):\*$/;function expandCapabilitySelectors(selectors,vocabulary=CAPABILITY_VOCABULARY){let expanded=[],seen=new Set,add2=__name(token=>{seen.has(token)||(seen.add(token),expanded.push(token))},"add");for(let selector of selectors){let namespace=CAPABILITY_NAMESPACE_SELECTOR.exec(selector)?.[1];if(!namespace){add2(selector);continue}let matches=vocabulary.filter(definition=>definition.declarable&&definition.token.startsWith(`${namespace}:`));if(matches.length===0){add2(selector);continue}for(let match of matches)add2(match.token)}return expanded}__name(expandCapabilitySelectors,"expandCapabilitySelectors");function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=expandCapabilitySelectors(parsed.data)}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&nonDeclarable.length===0,unknown,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z77}from"zod";var SurfaceGuardPolicySchema=z77.enum(["block","warn","allow"]),ClassificationSchema=z77.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z77.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z77.object({enabled:z77.boolean(),allowed_skills:z77.array(z77.string().min(1)).default([]),allowed_classifications:z77.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z77.enum(["off","daily","weekly"]),NotificationFormatSchema=z77.object({markdown:z77.boolean().default(!0),html:z77.boolean().default(!1)}),NotificationsPolicySchema=z77.object({email_recipients:z77.array(z77.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z77.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z77.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z78}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z78.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z78.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
|
|
1189
|
+
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs51 from"node:fs";import path52 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor,config){let value=Number(cursor??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page=await input.fetchPage(input.cursor);if(!input.allPages||page.nextCursor===null)return page;let items=[...page.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page.nextCursor!==null;){if(seen.has(page.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page.nextCursor),page=await input.fetchPage(page.nextCursor),items.push(...page.items)}return{...page,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z77}from"zod";var CapabilityTokenSchema=z77.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z77.array(CapabilityTokenSchema);import{z as z78}from"zod";var CronTriggerSchema=z78.object({type:z78.literal("schedule"),cron:z78.string().min(1,"cron expression required"),tz:z78.string().optional()}),ManualTriggerSchema2=z78.object({type:z78.literal("manual")}),WebhookTriggerSchema2=z78.object({type:z78.literal("webhook"),path:z78.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z78.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z78.object({name:z78.string().min(1),capability_grant:z78.enum(["inherit","explicit"]).optional(),explicit_grants:z78.array(z78.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z78.object({"sub-agents":z78.array(SubAgentRefSchema)}),RuntimeConfigSchema=z78.object({cloud:z78.boolean().optional(),dev:z78.boolean().optional(),long_running:z78.boolean().optional()}),DataSourceSchema=z78.enum(["main","prod"]),ConfigValueKeySchema=z78.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z78.preprocess(value=>typeof value=="string"?{key:value}:value,z78.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z78.boolean().default(!0),delivery:z78.literal("process_env").default("process_env")})),IntegrationKeySchema=z78.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z78.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z78.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z78.object({enabled:z78.boolean().default(!0),tools:z78.record(IntegrationToolKeySchema,z78.boolean()).optional()})),IntegrationPolicySchema=z78.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z78.object({version:z78.literal(1),description:z78.string().min(1).max(280).optional(),model:z78.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z78.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z78.array(DataSourceSchema).optional(),secrets:z78.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES,CAPABILITY_NAMESPACE_SELECTOR=/^([a-z][a-z0-9_]*):\*$/;function expandCapabilitySelectors(selectors,vocabulary=CAPABILITY_VOCABULARY){let expanded=[],seen=new Set,add2=__name(token=>{seen.has(token)||(seen.add(token),expanded.push(token))},"add");for(let selector of selectors){let namespace=CAPABILITY_NAMESPACE_SELECTOR.exec(selector)?.[1];if(!namespace){add2(selector);continue}let matches=vocabulary.filter(definition=>definition.declarable&&definition.token.startsWith(`${namespace}:`));if(matches.length===0){add2(selector);continue}for(let match of matches)add2(match.token)}return expanded}__name(expandCapabilitySelectors,"expandCapabilitySelectors");function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=expandCapabilitySelectors(parsed.data)}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown=[],nonDeclarable=[],highRisk=[];for(let token of expandCapabilitySelectors(tokens,vocab)){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&nonDeclarable.length===0,unknown,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z79}from"zod";var SurfaceGuardPolicySchema=z79.enum(["block","warn","allow"]),ClassificationSchema=z79.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z79.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z79.object({enabled:z79.boolean(),allowed_skills:z79.array(z79.string().min(1)).default([]),allowed_classifications:z79.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z79.enum(["off","daily","weekly"]),NotificationFormatSchema=z79.object({markdown:z79.boolean().default(!0),html:z79.boolean().default(!1)}),NotificationsPolicySchema=z79.object({email_recipients:z79.array(z79.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z79.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z79.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z80}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z80.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z80.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
|
|
1190
1190
|
${line}`):next2=(content2.endsWith(`
|
|
1191
1191
|
`)?content2:content2+`
|
|
1192
1192
|
`)+line+`
|
|
1193
1193
|
`,fs9.writeFileSync(configPath,next2)}__name(writeDescriptionToConfig,"writeDescriptionToConfig");async function createAgentCommand(name,options){try{let result=await createAgent({name,template:options.template,cwd:options.cwd,description:options.description,requireFimoProject:options.cwd===void 0});if(!result.ok){ui.error({command:"agents create",code:"AGENT_CREATE_FAILED",message:result.error??"Failed to scaffold agent."});return}let rel=path9.relative(process.cwd(),result.agentDir);ui.ok({command:"agents create",headline:`Created agent at ${rel}`,details:{agent:name,agent_dir:result.agentDir,relative_dir:rel},hint:"Next: `fimo agents validate "+name+"` then push to main to wire its triggers."})}catch(err){err instanceof InvalidAgentNameError?ui.error({command:"agents create",code:"INVALID_AGENT_NAME",message:err.message}):printBundleError("agents create",err)}}__name(createAgentCommand,"createAgentCommand");import path10 from"node:path";init_dist();init_api();init_config();async function agentIntegrationsCommand(name,opts){try{let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),bundle=await parseBundle(path10.join(resolveAgentBundlesDir(projectRoot),name)),policy=agentIntegrationPolicy(bundle.config),projectStatus=await loadProjectIntegrationStatus(opts,projectRoot),statusByKey=new Map(projectStatus.map(status=>[status.integrationKey,status])),keys=new Set([...Object.keys(policy),...projectStatus.map(status=>status.integrationKey)]);if(keys.size===0){ui.info({command:"agents integrations",message:`Agent '${name}' has no explicit integration policy and no project integrations were found.`});return}ui.table({command:"agents integrations",columns:[{key:"integration",label:"INTEGRATION"},{key:"project",label:"PROJECT"},{key:"agent",label:"AGENT"},{key:"tools",label:"TOOLS"}],rows:[...keys].sort().map(integrationKey=>{let entry=policy[integrationKey],status=statusByKey.get(integrationKey);return{integration:integrationKey,project:renderProjectStatus(status),agent:renderAgentPolicy(entry),tools:renderTools(entry)}})})}catch(err){printBundleError("agents integrations",err)}}__name(agentIntegrationsCommand,"agentIntegrationsCommand");async function loadProjectIntegrationStatus(opts,projectRoot){let projectId=opts.project??resolveFimoProject(projectRoot)?.settings.projectId;if(!projectId)return[];try{return await new FimoApiClient(loadConfig()).listProjectIntegrations(projectId)}catch{return[]}}__name(loadProjectIntegrationStatus,"loadProjectIntegrationStatus");function renderProjectStatus(status){return status?status.enabled?`enabled (${status.authModeLabel??status.authMode??"auth unknown"})`:status.installed?"disabled":"available":"unknown"}__name(renderProjectStatus,"renderProjectStatus");function renderAgentPolicy(entry){return entry&&entry.enabled?"enabled":"disabled"}__name(renderAgentPolicy,"renderAgentPolicy");function renderTools(entry){if(!entry?.enabled)return"no tools";if(entry.tools===void 0)return"all available tools";if(enabledAgentIntegrationTools(entry).length===0)return"no tools";let tools=entry?.tools??{};return Object.entries(tools).sort(([a],[b])=>a.localeCompare(b)).map(([tool,enabled])=>`${tool}:${enabled?"on":"off"}`).join(", ")}__name(renderTools,"renderTools");init_dist();async function listAgents(opts={}){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd());return(await listBundles(resolveAgentBundlesDir(projectRoot))).map(b=>({name:b.name,declared:!0,triggers:(b.config.triggers??[]).map(t2=>t2.type),capabilities:[...b.capabilities]}))}__name(listAgents,"listAgents");async function listAgentsCommand(opts={}){let agents;try{agents=await listAgents(opts)}catch(err){ui.error({command:"agents list",code:"AGENT_BUNDLE_LIST_FAILED",message:err.message});return}if(agents.length===0){ui.info({command:"agents list",message:"(no agents)",hint:"Run `fimo agents create <name>` to scaffold one."});return}ui.table({command:"agents list",columns:[{key:"name",label:"NAME"},{key:"triggers",label:"TRIGGERS"},{key:"capabilities",label:"CAPS"}],rows:agents.map(a=>({name:a.name,triggers:a.triggers.length===0?"\u2014":a.triggers.join(", "),capabilities:a.capabilities.length===0?"(read-only)":`${a.capabilities.length} caps`}))})}__name(listAgentsCommand,"listAgentsCommand");init_dist();async function agentLogsCommand(name,options){try{ui.result({command:"agents logs",data:{agent:name,session:options.session??null,streaming_available:!1,deferred_milestone:"M17"},render:__name(()=>[`Streaming logs for agent '${name}'${options.session?` \xB7 session ${options.session}`:""}\u2026`,"Log streaming endpoint not yet deployed (M17). No logs to show."].join(`
|
|
1194
|
-
`),"render"),warnings:["Log streaming endpoint not yet deployed (M17)."]})}catch(err){printBundleError("agents logs",err)}}__name(agentLogsCommand,"agentLogsCommand");init_esm();init_dist();init_api();init_config();init_branch_option();init_project();async function agentReportCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId(projectRoot);if(!projectId){ui.error({command:"agents report",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),api=new FimoApiClient(cfg),branch=selectBranchOption(options),session;try{if(options.session)session=await api.getAgentSession(projectId,options.session);else if(session=(await api.listAgentSessions(projectId,{agentName:name,branch,limit:1})).data[0],!session){ui.info({command:"agents report",message:`(no runs for '${name}'${branch?` on Branch '${branch}'`:""})`});return}}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents report",code:"AGENT_SESSION_FETCH_FAILED",message:`Failed to fetch session (HTTP ${err.status}): ${err.detail}`});return}throw err}let shortId2=session.id.slice(0,8),document=session.reportDocument
|
|
1194
|
+
`),"render"),warnings:["Log streaming endpoint not yet deployed (M17)."]})}catch(err){printBundleError("agents logs",err)}}__name(agentLogsCommand,"agentLogsCommand");init_esm();init_dist();init_api();init_config();init_branch_option();init_project();async function agentReportCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId(projectRoot);if(!projectId){ui.error({command:"agents report",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),api=new FimoApiClient(cfg),branch=selectBranchOption(options),session;try{if(options.session)session=await api.getAgentSession(projectId,options.session);else if(session=(await api.listAgentSessions(projectId,{agentName:name,branch,limit:1})).data[0],!session){ui.info({command:"agents report",message:`(no runs for '${name}'${branch?` on Branch '${branch}'`:""})`});return}}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents report",code:"AGENT_SESSION_FETCH_FAILED",message:`Failed to fetch session (HTTP ${err.status}): ${err.detail}`});return}throw err}let shortId2=session.id.slice(0,8),document=normalizeReportDocument(session.reportDocument);if(!document){ui.result({command:"agents report",data:{agent:name,session_id:session.id,short_id:shortId2,status:session.status,terminal_reason:session.terminalReason??null,report_document:null},render:__name(()=>{let lines=[];return lines.push(`! No report for '${name}' \xB7 session ${shortId2} (${session.status}).`),session.terminalReason?lines.push(` reason: ${session.terminalReason}`):session.status!=="finished"&&lines.push(" The run has not finished yet \u2014 a report is written when it completes."),lines.join(`
|
|
1195
1195
|
`)},"render")});return}ui.result({command:"agents report",data:{agent:name,session_id:session.id,status:session.status,report_document:document},render:__name(()=>`${`Report \xB7 ${name} \xB7 session ${session.id} \xB7 ${session.status}`}
|
|
1196
1196
|
|
|
1197
1197
|
${renderDocument(document,{details:options.details===!0,agentName:name,sessionId:session.id})}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(agentReportCommand,"agentReportCommand");function renderDocument(document,target){if(target.details)return flattenReportDocument(document);let brief=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)].join(`
|
|
@@ -1203,9 +1203,9 @@ Full report: fimo agents report ${target.agentName} --session ${target.sessionId
|
|
|
1203
1203
|
${result.driftLines.map(l=>` ${l}`).join(`
|
|
1204
1204
|
`)}`,hint:"Run `fimo deploy` to push them first, or `fimo agents run --skip-drift-check` to dispatch the deployed version anyway."});return}if(result.skipped){ui.info({command:"agents run",message:`Dispatch was skipped: ${result.skipped}`});return}if(result.sessionId){ui.ok({command:"agents run",headline:`Triggered ${name} (session ${result.sessionId})`,details:{agent:name,session_id:result.sessionId},hint:`Watch progress: fimo agents runs ${name}`});return}ui.error({command:"agents run",code:"UNEXPECTED_RUN_RESPONSE",message:"Unexpected response from server (no sessionId, no skipped)."})}catch(err){printBundleError("agents run",err)}}__name(runAgentCommand,"runAgentCommand");init_dist();init_api();init_config();init_branch_option();init_project();async function agentRunsCommand(name,options){try{let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:200}),projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId2(projectRoot);if(!projectId){ui.error({command:"agents runs",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let cfg=loadConfig(),api=new FimoApiClient(cfg),branch=selectBranchOption(options),page;try{page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let pageNumber=parseCursorNumber(cursor,{defaultValue:1,minimum:1}),response=await api.listAgentSessions(projectId,{agentName:name,branch,page:pageNumber,limit:pagination.limit});return{items:response.data,nextCursor:response.hasMore?String(response.page+1):null,total:response.total,page:response.page,totalPages:response.totalPages,hasMore:response.hasMore}},"fetchPage")})}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents runs",code:"AGENT_SESSIONS_FETCH_FAILED",message:`Failed to fetch sessions (HTTP ${err.status}): ${err.detail}`});return}throw err}let rows=page.items.map(session=>({id:session.id.slice(0,8),started:formatStartedAt(session.startedAt),duration:formatDuration(session.startedAt,session.finishedAt??session.cancelledAt),status:session.status,trigger:session.triggerKind,env:session.env,cost:`$${session.costUsd.toFixed(4)}`})),trailingArgs=[];branch&&trailingArgs.push("--branch",branch),options.project&&trailingArgs.push("--project",options.project),options.cwd&&trailingArgs.push("--cwd",options.cwd);let hint=page.nextCursor?buildPaginationHint(["fimo","agents","runs",name],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs}):void 0,jsonData={items:page.items,nextCursor:page.nextCursor,total:page.total,page:page.page,totalPages:page.totalPages,hasMore:page.hasMore};if(rows.length===0){ui.info({command:"agents runs",message:`(no recent sessions for '${name}'${branch?` on Branch '${branch}'`:""})`,jsonData});return}ui.table({command:"agents runs",columns:[{key:"id",label:"ID"},{key:"started",label:"STARTED"},{key:"duration",label:"DURATION"},{key:"status",label:"STATUS"},{key:"trigger",label:"TRIGGER"},{key:"env",label:"BRANCH"},{key:"cost",label:"COST"}],rows,jsonData,cellStyle:__name((row2,column)=>{if(column==="status")return statusRole(row2.status);if(column==="cost")return"dim"},"cellStyle"),...hint?{hint}:{}})}catch(err){if(err instanceof PaginationValidationError){ui.error({command:"agents runs",code:"AGENT_RUNS_INVALID_PAGINATION",message:err.message});return}printBundleError("agents runs",err)}}__name(agentRunsCommand,"agentRunsCommand");function readProjectId2(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId2,"readProjectId");function statusRole(status){switch(status){case"finished":return"success";case"errored":return"error";case"cancelled":return"warn";case"running":return"accent";default:return}}__name(statusRole,"statusRole");function formatStartedAt(startedAt){if(!startedAt)return"\u2014";let date=startedAt instanceof Date?startedAt:new Date(startedAt);return Number.isNaN(date.getTime())?"\u2014":date.toISOString().slice(0,16).replace("T"," ")}__name(formatStartedAt,"formatStartedAt");function formatDuration(startedAt,endedAt){if(!startedAt||!endedAt)return"\u2014";let start=startedAt instanceof Date?startedAt:new Date(startedAt),ms=(endedAt instanceof Date?endedAt:new Date(endedAt)).getTime()-start.getTime();if(Number.isNaN(ms)||ms<0)return"\u2014";if(ms<1e3)return`${ms}ms`;let secs=Math.floor(ms/1e3);if(secs<60)return`${secs}s`;let mins=Math.floor(secs/60),remainingSecs=secs%60;return`${mins}m${remainingSecs.toString().padStart(2,"0")}s`}__name(formatDuration,"formatDuration");init_dist();var import_yaml3=__toESM(require_dist(),1);import fs10 from"node:fs";import path12 from"node:path";var SECRET_KEY_RE=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_CONFIG_PREFIX2=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/;async function agentSecretsListCommand(name,opts){try{let config=readAgentConfig(name,opts.cwd),secrets=normalizeSecrets(config.secrets);if(secrets.length===0){ui.info({command:"agents secrets list",message:`No secrets requested by agent '${name}'.`});return}ui.table({command:"agents secrets list",columns:[{key:"key",label:"KEY"},{key:"requirement",label:"REQUIREMENT"},{key:"delivery",label:"DELIVERY"}],rows:secrets.map(secret=>({key:secret.key,requirement:secret.required===!1?"optional":"required",delivery:secret.delivery??"process_env"}))})}catch(err){printBundleError("agents secrets list",err)}}__name(agentSecretsListCommand,"agentSecretsListCommand");async function agentSecretsAddCommand(name,key,opts){try{validateSecretKey(key);let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),secrets=normalizeSecrets(config.secrets);secrets.some(secret=>secret.key===key)||(secrets.push({key,required:!opts.optional,delivery:"process_env"}),config.secrets=secrets,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config))),ui.ok({command:"agents secrets add",headline:`Agent '${name}' now requests secret ${key}`,details:{agent:name,key,optional:opts.optional===!0}})}catch(err){printBundleError("agents secrets add",err)}}__name(agentSecretsAddCommand,"agentSecretsAddCommand");async function agentSecretsRemoveCommand(name,key,opts){try{let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),after2=normalizeSecrets(config.secrets).filter(secret=>secret.key!==key);config.secrets=after2,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config)),ui.ok({command:"agents secrets remove",headline:`Agent '${name}' no longer requests secret ${key}`,details:{agent:name,key}})}catch(err){printBundleError("agents secrets remove",err)}}__name(agentSecretsRemoveCommand,"agentSecretsRemoveCommand");function normalizeSecrets(raw){if(!Array.isArray(raw))return[];let out=[];for(let item of raw){if(typeof item=="string"){out.push({key:item,required:!0,delivery:"process_env"});continue}if(item&&typeof item=="object"&&typeof item.key=="string"){let entry=item;out.push({key:entry.key,required:typeof entry.required=="boolean"?entry.required:!0,delivery:(entry.delivery==="process_env","process_env")})}}return out}__name(normalizeSecrets,"normalizeSecrets");function validateSecretKey(key){if(!SECRET_KEY_RE.test(key))throw new Error(`Secret key '${key}' must be UPPER_SNAKE_CASE.`);if(PUBLIC_CONFIG_PREFIX2.test(key))throw new Error(`Secret key '${key}' uses a public variable prefix. Use project variables for public values.`)}__name(validateSecretKey,"validateSecretKey");function readAgentConfig(name,cwd){return readAgentConfigWithPath(name,cwd).config}__name(readAgentConfig,"readAgentConfig");function readAgentConfigWithPath(name,cwd){let projectRoot=resolveProjectRoot(cwd??process.cwd()),filePath=path12.join(resolveAgentBundlesDir(projectRoot),name,"config.yaml");if(!fs10.existsSync(filePath))throw new Error(`Agent '${name}' does not have a config.yaml at ${filePath}.`);let parsed=(0,import_yaml3.parse)(fs10.readFileSync(filePath,"utf8")),config=parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:{};return{filePath,config}}__name(readAgentConfigWithPath,"readAgentConfigWithPath");init_dist();init_scaffold();async function listTemplatesCommand(){let templates=listAgentTemplates();if(templates.length===0){ui.info({command:"agents list-templates",message:"No agent templates bundled with this CLI."});return}ui.result({command:"agents list-templates",data:{templates},render:__name(()=>{let lines=["Available templates:"],longest=templates.reduce((acc,t2)=>Math.max(acc,t2.name.length),0);for(let t2 of templates){let padded=t2.name.padEnd(longest);lines.push(` ${padded} ${t2.goalFirstLine??"(no GOAL.md)"}`)}return lines.push(""),lines.push(" Use `fimo agents create <name> --template <template>` to scaffold."),lines.join(`
|
|
1205
1205
|
`)},"render")})}__name(listTemplatesCommand,"listTemplatesCommand");import fs11 from"node:fs";import path13 from"node:path";init_dist();init_api();init_auth();init_config();init_project_context();init_project();async function runValidateAgents(opts){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),agentsDir=resolveAgentBundlesDir(projectRoot),configPath=resolveProjectPolicyPath(projectRoot),policy=validatePolicy(configPath,projectRoot),bundleList=[];if(opts.name){if(!isValidAgentName(opts.name))return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[{pointer:"name",message:`Invalid agent name '${opts.name}'.`}]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};let bundle=await safeParse(path13.join(agentsDir,opts.name));if(!bundle.ok)return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[bundle.issue]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};bundleList=[bundle.bundle]}else bundleList=await listBundles(agentsDir);let reports=[],cloudNotifications=hasCloudNotificationRecipients(configPath);for(let bundle of bundleList){let report=validateOneBundle(bundle,bundleList);!cloudNotifications&&(bundle.config.triggers??[]).some(t2=>t2.type!=="manual")&&report.warnings.push({pointer:`${path13.basename(configPath)}:agents.notifications.email_recipients`,message:"Cloud triggers stay unwired until `agents.notifications.email_recipients` is non-empty (ADR-0009)."}),reports.push(report)}return{ok:(policy?.ok??!0)&&reports.every(r=>r.ok),policy,bundles:reports}}__name(runValidateAgents,"runValidateAgents");function hasCloudNotificationRecipients(policyPath){if(!fs11.existsSync(policyPath))return!1;try{return(parseFimoConfig(fs11.readFileSync(policyPath,"utf8"),{path:path13.basename(policyPath)}).agents?.notifications?.email_recipients??[]).length>0}catch{return!1}}__name(hasCloudNotificationRecipients,"hasCloudNotificationRecipients");function validatePolicy(policyPath,projectRoot){if(!fs11.existsSync(policyPath))return null;try{let text3=fs11.readFileSync(policyPath,"utf8");return parseFimoConfig(text3,{path:path13.relative(projectRoot,policyPath)}),{ok:!0,issues:[]}}catch(err){return{ok:!1,issues:[{pointer:path13.relative(projectRoot,policyPath),message:err.message,remediation:err.remediation}]}}}__name(validatePolicy,"validatePolicy");async function safeParse(bundlePath){try{return{ok:!0,bundle:await parseBundle(bundlePath)}}catch(err){return{ok:!1,issue:{pointer:path13.basename(bundlePath),message:err.message,remediation:err.remediation}}}}__name(safeParse,"safeParse");function validateOneBundle(bundle,allBundles){let phases={parse:{ok:!0,issues:[]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},vocab=validateAgainstVocabulary(bundle.capabilities,CAPABILITY_VOCABULARY);for(let token of vocab.unknown){let suggestion=suggestCapability(token),err=new BundleInvalidCapabilityError(token,"unknown",{suggestion:suggestion??void 0});phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}for(let token of vocab.nonDeclarable){let err=new BundleInvalidCapabilityError(token,"runtime_only");phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}let agentMap=new Map(allBundles.map(b=>[b.name,b])),compositionResult=composition_exports.validateComposition(bundle,agentMap);if(compositionResult.cycle){let err=new BundleCompositionCycleError(compositionResult.cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}for(let missingName of compositionResult.missing)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${missingName}]`,message:`Sub-agent '${missingName}' is referenced but not present in the project's agent-bundle directory.`,remediation:`Run \`fimo agents create ${missingName}\` or remove the reference from composition.sub-agents.`});for(let invalid of compositionResult.invalidGrants)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${invalid.subAgentName}].explicit_grants`,message:`explicit_grants references capabilities the sub-agent never declared: [${invalid.invalid.join(", ")}]. Declared: [${invalid.declared.join(", ")}].`,remediation:"Remove the undeclared tokens from explicit_grants, or add them to the sub-agent's capabilities.yaml."});if(!compositionResult.cycle){let cycle=detectCompositionCycle({root:bundle,agentMap});if(cycle){let err=new BundleCompositionCycleError(cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}}let issues=validateBundle(bundle,{availableAgents:allBundles}),warnings=[...bundle.warnings];for(let issue of issues){if(issue.severity==="warning"){warnings.push({pointer:issue.pointer,message:issue.message});continue}issue.pointer.startsWith("capabilities.yaml")||issue.pointer.startsWith("config.yaml:composition")||(phases.semantics.ok=!1,phases.semantics.issues.push({pointer:issue.pointer,message:issue.message}))}let ok=phases.parse.ok&&phases.capabilities.ok&&phases.composition.ok&&phases.semantics.ok;return{name:bundle.name,ok,phases,warnings}}__name(validateOneBundle,"validateOneBundle");async function runAvailabilityChecks(cwd){let projectRoot=resolveProjectRoot(cwd),projectId;try{projectId=loadProjectSettings(projectRoot).projectId}catch{if(projectId=process.env.FIMO_PROJECT_ID?.trim()??"",!projectId)return{ok:!0,skippedReason:"not-linked",issues:[]}}if(!process.env.FIMO_API_TOKEN?.trim()&&!readCredentials())return{ok:!0,skippedReason:"not-signed-in",issues:[]};let api=new FimoApiClient(loadConfig()),context=await getProjectContext({cwd:projectRoot}),environment=await api.resolveProjectEnvironmentKey(projectId,context.branch),agentsDir=resolveAgentBundlesDir(projectRoot),bundles=await listBundles(agentsDir),issues=[],configPath=__name(agentName=>path13.relative(projectRoot,path13.join(agentsDir,agentName,"config.yaml")).replaceAll("\\","/"),"configPath"),integrationsByAgent=bundles.map(bundle=>({name:bundle.name,integrations:Object.entries(agentIntegrationPolicy(bundle.config)).map(([integrationKey,entry])=>({integrationKey,enabled:entry.enabled,tools:enabledAgentIntegrationTools(entry),allTools:entry.tools===void 0,toolsConfigured:entry.tools!==void 0})).filter(entry=>entry.enabled)})).filter(entry=>entry.integrations.length>0);if(integrationsByAgent.length>0){let statuses=await api.listProjectIntegrations(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),infoByKey=new Map;for(let agent of integrationsByAgent)for(let integration of agent.integrations){let file=configPath(agent.name),status=statusByKey.get(integration.integrationKey);if(!status){issues.push({pointer:file,message:`${agent.name} allows unsupported integration ${integration.integrationKey}.`});continue}integration.toolsConfigured&&integration.tools.length===0&&issues.push({pointer:file,message:`${agent.name} enables ${integration.integrationKey}, but its tools map allows none. Remove the tools map to allow all available tools, or set at least one integrations.${integration.integrationKey}.tools.<tool>: true entry.`}),status.enabled||issues.push({pointer:file,message:`${agent.name} allows ${integration.integrationKey}, but the project integration is not enabled. Run: fimo integrations enable ${integration.integrationKey}`});let info=infoByKey.get(integration.integrationKey)??await api.getProjectIntegrationInfo(projectId,integration.integrationKey);infoByKey.set(integration.integrationKey,info);let knownTools=new Set(info.tools.map(tool=>tool.key)),effectiveTools=integration.allTools?[...knownTools]:integration.tools;for(let tool of effectiveTools)knownTools.has(tool)||issues.push({pointer:file,message:`${agent.name} allows unknown ${integration.integrationKey}.${tool} tool. Supported tools: ${[...knownTools].sort().join(", ")}`})}}let secretsByAgent=bundles.map(bundle=>({name:bundle.name,keys:(bundle.config.secrets??[]).filter(secret=>secret.required!==!1).map(secret=>secret.key)})).filter(entry=>entry.keys.length>0);if(secretsByAgent.length>0){let defined=new Set((await api.listProjectSecretEntries(projectId,{kind:"secret",environment})).map(secret=>secret.key));for(let entry of secretsByAgent)for(let key of entry.keys)defined.has(key)||issues.push({pointer:configPath(entry.name),message:`${entry.name} requires project secret ${key}, but it is not set. Run: fimo secrets add ${key} --stdin`})}return{ok:issues.length===0,skippedReason:null,issues}}__name(runAvailabilityChecks,"runAvailabilityChecks");async function validateAgentsCommand(opts){let report;try{report=await runValidateAgents(opts)}catch(err){throw printBundleError("agents validate",err),opts.noExit||(process.exitCode=1),err}return report.bundles.length===0&&!report.policy?(ui.info({command:"agents validate",message:"No bundles or Fimo project config found."}),report):(report.availability=await runAvailabilityChecks(opts.cwd??process.cwd()),report.availability.ok||(report.ok=!1),ui.result({command:"agents validate",data:report,render:__name(()=>renderReportHuman(report),"render")}),!report.ok&&!opts.noExit&&(process.exitCode=1),report)}__name(validateAgentsCommand,"validateAgentsCommand");function renderReportHuman(report){let lines=[];if(report.policy)if(report.policy.ok)lines.push(" \u2713 Fimo config policy ok");else{lines.push(" \u2717 Fimo config");for(let issue of report.policy.issues)lines.push(` \u2717 ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}for(let bundle of report.bundles)if(bundle.ok){lines.push(` \u2713 ${bundle.name} all phases ok`);for(let w3 of bundle.warnings)lines.push(` ! ${w3.pointer}: ${w3.message}`)}else{lines.push(` \u2717 ${bundle.name}`);for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)lines.push(` \u2717 [${phase}] ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}if(report.availability)if(report.availability.skippedReason){let why=report.availability.skippedReason==="not-signed-in"?"not signed in \u2014 run `fimo login`":"no linked project";lines.push(` \u21B7 integrations & secrets \u2014 skipped (${why})`)}else if(report.availability.ok)lines.push(" \u2713 integrations & secrets available");else{lines.push(" \u2717 integrations & secrets");for(let issue of report.availability.issues)lines.push(` \u2717 ${issue.message}`)}return lines.join(`
|
|
1206
|
-
`)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--branch <branch>","Target Branch (default: main)").option("--env <branch>","Deprecated alias for --branch").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),addPaginationOptions(agents.command("runs <name>").description("Paginated session list"),{defaultLimit:20,maxLimit:200}).option("--branch <branch>","Filter sessions to a specific Branch").option("--env <branch>","Deprecated alias for --branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report brief; latest run unless --session is given").option("--session <id>","Target a specific session id").option("--details","Print the report's full evidence section as well as its brief").option("--branch <branch>","Pick the latest run on a specific Branch").option("--env <branch>","Deprecated alias for --branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist5();init_dist();import fs12 from"node:fs";import path14 from"node:path";import{z as z81}from"zod";init_interactive();init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z81.object({sourceId:z81.string().min(1),path:z81.string().min(1),name:z81.string().min(1).optional(),parentId:z81.string().min(1).optional(),folderPath:z81.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z81.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index2,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index2,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item){let filePath=path14.resolve(cwd,item.path);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=path14.basename(filePath),formData=new FormData,mimeType=path14.extname(fileName).toLowerCase()===".svg"?"image/svg+xml":void 0;return formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),item.name&&formData.append("name",item.name),item.parentId&&formData.append("parentId",item.parentId),item.folderPath&&formData.append("folderPath",item.folderPath),formData}__name(buildAssetFormData,"buildAssetFormData");function readBulkUploadManifest(cwd,manifest){let manifestPath=path14.resolve(cwd,manifest);if(!fs12.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs12.readFileSync(manifestPath,"utf8"))}catch(error){throw new Error(`Could not parse asset manifest ${manifestPath}`,{cause:error})}let result=bulkUploadManifestSchema.safeParse(parsed);if(!result.success){let issues=result.error.issues.map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw new Error(`Invalid asset manifest:
|
|
1206
|
+
`)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--branch <branch>","Target Branch (default: main)").option("--env <branch>","Deprecated alias for --branch").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),addPaginationOptions(agents.command("runs <name>").description("Paginated session list"),{defaultLimit:20,maxLimit:200}).option("--branch <branch>","Filter sessions to a specific Branch").option("--env <branch>","Deprecated alias for --branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report brief; latest run unless --session is given").option("--session <id>","Target a specific session id").option("--details","Print the report's full evidence section as well as its brief").option("--branch <branch>","Pick the latest run on a specific Branch").option("--env <branch>","Deprecated alias for --branch").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist5();init_dist();import fs12 from"node:fs";import path14 from"node:path";import{z as z83}from"zod";init_interactive();init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z83.object({sourceId:z83.string().min(1),path:z83.string().min(1),name:z83.string().min(1).optional(),parentId:z83.string().min(1).optional(),folderPath:z83.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z83.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index2,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index2,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item){let filePath=path14.resolve(cwd,item.path);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=path14.basename(filePath),formData=new FormData,mimeType=path14.extname(fileName).toLowerCase()===".svg"?"image/svg+xml":void 0;return formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),item.name&&formData.append("name",item.name),item.parentId&&formData.append("parentId",item.parentId),item.folderPath&&formData.append("folderPath",item.folderPath),formData}__name(buildAssetFormData,"buildAssetFormData");function readBulkUploadManifest(cwd,manifest){let manifestPath=path14.resolve(cwd,manifest);if(!fs12.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs12.readFileSync(manifestPath,"utf8"))}catch(error){throw new Error(`Could not parse asset manifest ${manifestPath}`,{cause:error})}let result=bulkUploadManifestSchema.safeParse(parsed);if(!result.success){let issues=result.error.issues.map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw new Error(`Invalid asset manifest:
|
|
1207
1207
|
${issues.join(`
|
|
1208
|
-
`)}`)}return result.data}__name(readBulkUploadManifest,"readBulkUploadManifest");function parseConcurrency(value){let concurrency=Number(value);if(!Number.isInteger(concurrency)||concurrency<1||concurrency>16)throw new Error("--concurrency must be an integer between 1 and 16");return concurrency}__name(parseConcurrency,"parseConcurrency");async function mapWithConcurrency(items,concurrency,run){let results=new Array(items.length),nextIndex=0;return await Promise.all(Array.from({length:Math.min(concurrency,items.length)},async()=>{for(;nextIndex<items.length;){let index2=nextIndex;nextIndex+=1,results[index2]=await run(items[index2])}})),results}__name(mapWithConcurrency,"mapWithConcurrency");async function assetsListCommand(options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,branch:ctx.branch});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),params.limit=String(pagination.limit);let initialOffset=parseCursorNumber(pagination.cursor,{defaultValue:0,minimum:0}),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let offset=parseCursorNumber(cursor,{defaultValue:0,minimum:0}),response=await api.listAssets(ctx.projectId,{...params,offset:String(offset)});return toOffsetPaginationPage(response)},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=assetPaginationTrailingArgs(options,ctx.branch);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","assets","list"],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(assetsListCommand,"assetsListCommand");function assetPaginationTrailingArgs(options,branch){let args=[];for(let[flag2,value]of[["--branch",branch],["--parent-id",options.parentId],["--search",options.search],["--type",options.type],["--mime-prefix",options.mimePrefix],["--sort-by",options.sortBy],["--cwd",options.cwd]])value!==void 0&&args.push(flag2,value);for(let[flag2,enabled]of[["--image",options.image],["--video",options.video],["--audio",options.audio]])enabled&&args.push(flag2);return args}__name(assetPaginationTrailingArgs,"assetPaginationTrailingArgs");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let result=await api.uploadAsset(ctx.projectId,buildAssetFormData(cwd,{path:file,name:options.name,parentId:options.parentId,folderPath:options.folderPath}));ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsBulkUploadCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),items=readBulkUploadManifest(cwd,options.file),concurrency=parseConcurrency(options.concurrency),{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let uploaded=await mapWithConcurrency(items,concurrency,async item=>{try{let asset=await api.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item));return{sourceId:item.sourceId,path:item.path,status:"uploaded",asset}}catch(error){return{sourceId:item.sourceId,path:item.path,status:"failed",error:error instanceof Error?error.message:String(error)}}}),failed=uploaded.filter(item=>item.status==="failed").length,result={total:uploaded.length,uploaded:uploaded.length-failed,failed,items:uploaded};ui.result({command:"assets bulk-upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")}),failed>0&&(process.exitCode=1)}__name(assetsBulkUploadCommand,"assetsBulkUploadCommand");async function assetsReadCommand(id,options,cmd){if(options.cursor!==void 0&&options.query!==void 0)throw new Error("--cursor and --query are mutually exclusive");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.read",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.readAsset(ctx.projectId,id,{cursor:options.cursor,query:options.query});ui.result({command:"assets read",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsReadCommand,"assetsReadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.createFolder(ctx.projectId,name,options.parentId);ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");var OTHER_BRANCHES_CAVEAT="Other Branches are not checked. This result is guidance for Current, Main, and Live, not a global unused claim.";function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope=>[scope.scope,scope.references.length])),referenceCount=scopes.reduce((total,scope)=>total+scope.references.length,0);return{status:scopes.some(scope=>scope.coverage!=="complete"||scope.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope=>[scope.scope,scope.coverage])),counts,referenceCount,scopes,otherBranches:{checked:!1,caveat:OTHER_BRANCHES_CAVEAT}}}__name(summarizeImpact,"summarizeImpact");async function loadAssetImpact(api,projectId,id){let events=await api.getAssetReferenceImpact(projectId,{assetIds:[id],scopes:["current","main","live"]}),complete=events.some(event=>event.type==="complete"),scopes=events.filter(event=>event.type==="scope").map(event=>event.data);if(!complete||scopes.length!==3)throw new Error("Asset usage scan ended before Current, Main, and Live were reported");return summarizeImpact(scopes)}__name(loadAssetImpact,"loadAssetImpact");async function assetsUsageCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await loadAssetImpact(api,ctx.projectId,id);ui.result({command:"assets usage",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUsageCommand,"assetsUsageCommand");async function assetsReplaceCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.replaceAssetReferences(ctx.projectId,id,options.with),receipt={sourceAssetId:id,replacementAssetId:options.with,scope:"current",...result,sourceRemoved:!1};ui.result({command:"assets replace",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsReplaceCommand,"assetsReplaceCommand");async function assetsRemoveCommand(id,options,cmd){if(options.permanent&&options.withoutChecking)throw new Error("--permanent cannot be combined with --without-checking");if(options.replaceWith&&options.withoutChecking)throw new Error("--replace-with and --without-checking are mutually exclusive");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch}),options.permanent){if(options.replaceWith&&await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch}),!options.yes){assertInteractive("Pass --yes to permanently destroy the asset without a prompt.","assets remove");let confirmed=await ot2({message:options.replaceWith?`Point references everywhere at ${options.replaceWith}, then permanently destroy asset ${id} across the project? This cannot be undone.`:`Permanently destroy asset ${id} across the project? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"assets remove",message:"Cancelled."});return}}if(options.replaceWith){let replacement2=await api.destroyAssetWithReplacement(ctx.projectId,id,options.replaceWith),receipt3={assetId:id,scope:"project",permanent:!0,removed:!0,replacement:{assetId:options.replaceWith,...replacement2}};ui.result({command:"assets remove",data:receipt3,render:__name(()=>renderPrettyJson3(receipt3),"render")});return}await api.destroyAsset(ctx.projectId,id);let receipt2={assetId:id,scope:"project",permanent:!0,removed:!0};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}let usage,usageError,replacement;if(options.replaceWith){await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let preview=await api.previewAssetReferenceReplacement(ctx.projectId,id,options.replaceWith),applied=await api.replaceAssetReferences(ctx.projectId,id,options.replaceWith);if(preview.referencesReplaced!==applied.referencesReplaced||preview.entriesChanged!==applied.entriesChanged)throw new Error("Current Branch references changed during replacement; the source asset was not removed");replacement=applied}else if(!options.withoutChecking)try{usage=await loadAssetImpact(api,ctx.projectId,id)}catch(error){usageError={message:error instanceof Error?error.message:String(error)}}await api.deleteAsset(ctx.projectId,id);let receipt={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!0,checked:!options.withoutChecking,usage,usageError,replacement:options.replaceWith?{assetId:options.replaceWith,...replacement}:void 0};ui.result({command:"assets remove",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsRemoveCommand,"assetsRemoveCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_BRANCH2="main";var BRANCH_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidBranch2(branch){return typeof branch!="string"||branch.length===0||branch.length>255||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX2.test(branch)}__name(isValidBranch2,"isValidBranch");function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}__name(fnv1a82,"fnv1a8");function envResourceKey2(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(branch);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}__name(buildTenantApiUrl2,"buildTenantApiUrl");var LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.branch]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let gitBranch=currentBranch2(root2),branch=gitBranch??DEFAULT_BRANCH2,tenantApiUrl=buildTenantApiUrl2(link.projectId,branch,link.tenantApiBaseUrl);return{env:branch,tenantApiUrl,source:gitBranch?"branch":"fallback",values:buildLocalRuntimeEnv({tenantApiUrl,branch}),link}}__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}__name(findStaleFimoOverride,"findStaleFimoOverride");function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}__name(staleOverrideMessage,"staleOverrideMessage");function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");function readLocalEnvFiles(cwd){let root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,file);if(fs13.existsSync(filePath))for(let line of fs13.readFileSync(filePath,"utf-8").split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&branch!=="HEAD"&&isValidBranch2(branch)?branch:null}catch{return null}}__name(currentBranch2,"currentBranch");function findProjectRoot2(start){let dir=path15.resolve(start);for(;;){if(fs13.existsSync(path15.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs13.existsSync(path15.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,layout.project);if(fs13.existsSync(file))try{let parsed=JSON.parse(fs13.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}__name(readProjectLink,"readProjectLink");init_api();init_config();init_git();init_project_context();init_esm();function buildPreviewUrl(webUrl,projectId,branch){return new URL(`/preview/${encodeURIComponent(projectId)}/${encodeBranchPathSegment(branch)}`,webUrl).toString()}__name(buildPreviewUrl,"buildPreviewUrl");function buildProjectPreviewUrl(webUrl,projectId,branch){return new URL(`/app/projects/${encodeURIComponent(projectId)}/branch/${encodeURIComponent(branch)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();function branchOverride(program2){return branchOverrideFromCommand(program2)}__name(branchOverride,"branchOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),branches=await new FimoApiClient().withBranch(ctx.branch).listBranches(ctx.projectId,{includeDeleted:opts.verbose,includeAgentBranches:opts.all});if(branches.length===0){ui.info({command:"branch",message:"(no Branches yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:[{key:"branch",label:"BRANCH"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:branches.map(row2=>({branch:branchNameOf(row2),status:row2.status,parent:parentBranchOf(row2)??"\u2014"})),isActive:__name(row2=>row2.branch===ctx.branch,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),api=new FimoApiClient().withBranch(ctx.branch),parentBranch=opts.from??ctx.branch;if(isProductionBranch(name)||isProductionBranch(parentBranch)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentBranch(api,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let project=await api.getProject(ctx.projectId),created=await api.createBranch(ctx.projectId,{branch:name,parentBranch}),createdBranch=branchNameOf(created),previewUrl=project.previewEnabled===!1?null:buildPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),headline=`Created Branch '${createdBranch}' (status: ${created.status})`;ui.result({command:"branch",data:{headline,details:{branch:createdBranch,parent_branch:parentBranch,env:createdBranch,parent_env:parentBranch,status:created.status,preview_url:previewUrl,studio_url:studioUrl,dashboard_url:studioUrl}},render:__name(context=>renderBranchCreated({headline,parentBranch,previewUrl,studioUrl},context),"render")})}__name(branchCreateCommand,"branchCreateCommand");function renderBranchCreated(result,context){let lines=[`${context.ascii?"[ok]":"\u2713"} ${result.headline}`,` Parent: ${result.parentBranch}`];return result.previewUrl&&lines.push(` Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),lines.push(` Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.join(`
|
|
1208
|
+
`)}`)}return result.data}__name(readBulkUploadManifest,"readBulkUploadManifest");function parseConcurrency(value){let concurrency=Number(value);if(!Number.isInteger(concurrency)||concurrency<1||concurrency>16)throw new Error("--concurrency must be an integer between 1 and 16");return concurrency}__name(parseConcurrency,"parseConcurrency");async function mapWithConcurrency(items,concurrency,run){let results=new Array(items.length),nextIndex=0;return await Promise.all(Array.from({length:Math.min(concurrency,items.length)},async()=>{for(;nextIndex<items.length;){let index2=nextIndex;nextIndex+=1,results[index2]=await run(items[index2])}})),results}__name(mapWithConcurrency,"mapWithConcurrency");async function assetsListCommand(options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,branch:ctx.branch});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),params.limit=String(pagination.limit);let initialOffset=parseCursorNumber(pagination.cursor,{defaultValue:0,minimum:0}),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let offset=parseCursorNumber(cursor,{defaultValue:0,minimum:0}),response=await api.listAssets(ctx.projectId,{...params,offset:String(offset)});return toOffsetPaginationPage(response)},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=assetPaginationTrailingArgs(options,ctx.branch);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","assets","list"],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(assetsListCommand,"assetsListCommand");function assetPaginationTrailingArgs(options,branch){let args=[];for(let[flag2,value]of[["--branch",branch],["--parent-id",options.parentId],["--search",options.search],["--type",options.type],["--mime-prefix",options.mimePrefix],["--sort-by",options.sortBy],["--cwd",options.cwd]])value!==void 0&&args.push(flag2,value);for(let[flag2,enabled]of[["--image",options.image],["--video",options.video],["--audio",options.audio]])enabled&&args.push(flag2);return args}__name(assetPaginationTrailingArgs,"assetPaginationTrailingArgs");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let result=await api.uploadAsset(ctx.projectId,buildAssetFormData(cwd,{path:file,name:options.name,parentId:options.parentId,folderPath:options.folderPath}));ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsBulkUploadCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),items=readBulkUploadManifest(cwd,options.file),concurrency=parseConcurrency(options.concurrency),{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let uploaded=await mapWithConcurrency(items,concurrency,async item=>{try{let asset=await api.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item));return{sourceId:item.sourceId,path:item.path,status:"uploaded",asset}}catch(error){return{sourceId:item.sourceId,path:item.path,status:"failed",error:error instanceof Error?error.message:String(error)}}}),failed=uploaded.filter(item=>item.status==="failed").length,result={total:uploaded.length,uploaded:uploaded.length-failed,failed,items:uploaded};ui.result({command:"assets bulk-upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")}),failed>0&&(process.exitCode=1)}__name(assetsBulkUploadCommand,"assetsBulkUploadCommand");async function assetsReadCommand(id,options,cmd){if(options.cursor!==void 0&&options.query!==void 0)throw new Error("--cursor and --query are mutually exclusive");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.read",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.readAsset(ctx.projectId,id,{cursor:options.cursor,query:options.query});ui.result({command:"assets read",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsReadCommand,"assetsReadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.createFolder(ctx.projectId,name,options.parentId);ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");var OTHER_BRANCHES_CAVEAT="Other Branches are not checked. This result is guidance for Current, Main, and Live, not a global unused claim.",scopeCount=__name(scope=>scope.referenceCount??scope.references.length,"scopeCount");function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope=>[scope.scope,scopeCount(scope)])),referenceCount=scopes.reduce((total,scope)=>total+scopeCount(scope),0),codeReferenceCount=scopes.reduce((total,scope)=>total+(scope.codeReferenceCount??0),0);return{status:scopes.some(scope=>scope.coverage!=="complete"||scope.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope=>[scope.scope,scope.coverage])),counts,referenceCount,codeReferenceCount,scopes,otherBranches:{checked:!1,caveat:OTHER_BRANCHES_CAVEAT}}}__name(summarizeImpact,"summarizeImpact");async function loadAssetImpact(api,projectId,id){let events=await api.getAssetReferenceImpact(projectId,{assetIds:[id],scopes:["current","main","live"]}),complete=events.some(event=>event.type==="complete"),scopes=events.filter(event=>event.type==="scope").map(event=>event.data);if(!complete||scopes.length!==3)throw new Error("Asset usage scan ended before Current, Main, and Live were reported");return summarizeImpact(scopes)}__name(loadAssetImpact,"loadAssetImpact");async function assetsUsageCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await loadAssetImpact(api,ctx.projectId,id);ui.result({command:"assets usage",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUsageCommand,"assetsUsageCommand");async function assetsReplaceCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.replaceAssetReferences(ctx.projectId,id,options.with),receipt={sourceAssetId:id,replacementAssetId:options.with,scope:"current",...result,sourceRemoved:!1};ui.result({command:"assets replace",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsReplaceCommand,"assetsReplaceCommand");async function assetsRemoveCommand(id,options,cmd){if(options.permanent&&options.withoutChecking)throw new Error("--permanent cannot be combined with --without-checking");if(options.replaceWith&&options.withoutChecking)throw new Error("--replace-with and --without-checking are mutually exclusive");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch}),options.permanent){if(options.replaceWith&&await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch}),!options.yes){assertInteractive("Pass --yes to permanently destroy the asset without a prompt.","assets remove");let confirmed=await ot2({message:options.replaceWith?`Point references everywhere at ${options.replaceWith}, then permanently destroy asset ${id} across the project? This cannot be undone.`:`Permanently destroy asset ${id} across the project? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"assets remove",message:"Cancelled."});return}}if(options.replaceWith){let replacement=await api.destroyAssetWithReplacement(ctx.projectId,id,options.replaceWith),receipt3={assetId:id,scope:"project",permanent:!0,removed:!0,replacement:{assetId:options.replaceWith,...replacement}};ui.result({command:"assets remove",data:receipt3,render:__name(()=>renderPrettyJson3(receipt3),"render")});return}await api.destroyAsset(ctx.projectId,id);let receipt2={assetId:id,scope:"project",permanent:!0,removed:!0};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}if(options.replaceWith){await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let outcome=await api.replaceAndRemoveAsset(ctx.projectId,id,options.replaceWith),receipt2={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!1,removal:{operationId:outcome.id,expiresAt:outcome.expiresAt,undoable:outcome.undoable},replacement:{assetId:options.replaceWith,code:outcome.codeReplacement}};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}let usage,usageError;if(!options.withoutChecking)try{usage=await loadAssetImpact(api,ctx.projectId,id)}catch(error){usageError={message:error instanceof Error?error.message:String(error)}}await api.deleteAsset(ctx.projectId,id);let receipt={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!0,checked:!options.withoutChecking,usage,usageError};ui.result({command:"assets remove",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsRemoveCommand,"assetsRemoveCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_BRANCH2="main";var BRANCH_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidBranch2(branch){return typeof branch!="string"||branch.length===0||branch.length>255||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX2.test(branch)}__name(isValidBranch2,"isValidBranch");function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}__name(fnv1a82,"fnv1a8");function envResourceKey2(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(branch);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}__name(buildTenantApiUrl2,"buildTenantApiUrl");var LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.branch]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let gitBranch=currentBranch2(root2),branch=gitBranch??DEFAULT_BRANCH2,tenantApiUrl=buildTenantApiUrl2(link.projectId,branch,link.tenantApiBaseUrl);return{env:branch,tenantApiUrl,source:gitBranch?"branch":"fallback",values:buildLocalRuntimeEnv({tenantApiUrl,branch}),link}}__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}__name(findStaleFimoOverride,"findStaleFimoOverride");function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}__name(staleOverrideMessage,"staleOverrideMessage");function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");function readLocalEnvFiles(cwd){let root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,file);if(fs13.existsSync(filePath))for(let line of fs13.readFileSync(filePath,"utf-8").split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&branch!=="HEAD"&&isValidBranch2(branch)?branch:null}catch{return null}}__name(currentBranch2,"currentBranch");function findProjectRoot2(start){let dir=path15.resolve(start);for(;;){if(fs13.existsSync(path15.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs13.existsSync(path15.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,layout.project);if(fs13.existsSync(file))try{let parsed=JSON.parse(fs13.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}__name(readProjectLink,"readProjectLink");init_api();init_config();init_git();init_project_context();init_esm();function buildPreviewUrl(webUrl,projectId,branch){return new URL(`/preview/${encodeURIComponent(projectId)}/${encodeBranchPathSegment(branch)}`,webUrl).toString()}__name(buildPreviewUrl,"buildPreviewUrl");function buildProjectPreviewUrl(webUrl,projectId,branch){return new URL(`/app/projects/${encodeURIComponent(projectId)}/branch/${encodeURIComponent(branch)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();function branchOverride(program2){return branchOverrideFromCommand(program2)}__name(branchOverride,"branchOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),branches=await new FimoApiClient().withBranch(ctx.branch).listBranches(ctx.projectId,{includeDeleted:opts.verbose,includeAgentBranches:opts.all});if(branches.length===0){ui.info({command:"branch",message:"(no Branches yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:[{key:"branch",label:"BRANCH"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:branches.map(row2=>({branch:branchNameOf(row2),status:row2.status,parent:parentBranchOf(row2)??"\u2014"})),isActive:__name(row2=>row2.branch===ctx.branch,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),api=new FimoApiClient().withBranch(ctx.branch),parentBranch=opts.from??ctx.branch;if(isProductionBranch(name)||isProductionBranch(parentBranch)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentBranch(api,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let project=await api.getProject(ctx.projectId),created=await api.createBranch(ctx.projectId,{branch:name,parentBranch}),createdBranch=branchNameOf(created),previewUrl=project.previewEnabled===!1?null:buildPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),headline=`Created Branch '${createdBranch}' (status: ${created.status})`;ui.result({command:"branch",data:{headline,details:{branch:createdBranch,parent_branch:parentBranch,env:createdBranch,parent_env:parentBranch,status:created.status,preview_url:previewUrl,studio_url:studioUrl,dashboard_url:studioUrl}},render:__name(context=>renderBranchCreated({headline,parentBranch,previewUrl,studioUrl},context),"render")})}__name(branchCreateCommand,"branchCreateCommand");function renderBranchCreated(result,context){let lines=[`${context.ascii?"[ok]":"\u2713"} ${result.headline}`,` Parent: ${result.parentBranch}`];return result.previewUrl&&lines.push(` Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),lines.push(` Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.join(`
|
|
1209
1209
|
`)}__name(renderBranchCreated,"renderBranchCreated");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({branchOverride:branchOverride(program2)}),api=new FimoApiClient().withBranch(ctx.branch);if(name===DEFAULT_BRANCH){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default Branch '${DEFAULT_BRANCH}'.`});return}if(isProductionBranch(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be deleted.`});return}await api.deleteBranch(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{branch:name,env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),api=new FimoApiClient().withBranch(ctx.branch),cwd=resolveProjectCwd();if(isProductionBranch(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentBranch=opts.from??ctx.branch,parentValidation=await validateParentBranch(api,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createBranch(ctx.projectId,{branch:name,parentBranch}),created=!0}else await api.getBranch(ctx.projectId,name);let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}let runtime=resolveLocalRuntimeEnv({cwd});ui.ok({command:"checkout",headline:`Now on Branch '${name}'`,details:{branch:name,created,git_switched:gitSwitched,parent_branch:opts.from??null,env:name,parent_env:opts.from??null,tenant_api_url:runtime?.tenantApiUrl??null},warnings:describeRuntimeWarnings(cwd,runtime)})}__name(checkoutCommand,"checkoutCommand");function describeRuntimeWarnings(cwd,runtime){if(!runtime)return["This checkout cannot derive its tenant API URL \u2014 the project link predates that. Run `fimo link` once to record it; until then the app keeps whatever runtime env values it already has."];let stale=findStaleFimoOverride({...readLocalEnvFiles(cwd),...process.env},runtime);return stale?[staleOverrideMessage(stale)]:void 0}__name(describeRuntimeWarnings,"describeRuntimeWarnings");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),api=new FimoApiClient().withBranch(ctx.branch),{branch,conflicts}=await api.syncBranch(ctx.projectId,ctx.branch,{from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0,synced=branchNameOf(branch);ui.ok({command:"pull",headline:`Branch '${synced}' synced`,details:{branch:synced,env:synced,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentBranch(api,projectId,parentBranch,ctx,fromFlag){try{return await api.getBranch(projectId,parentBranch),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active Branch (\`${ctx.branch}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.branch}\`)`:ctx.source==="tag"?`the release tag \`${ctx.branch}\``:`the project default (\`${ctx.branch}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing Branch via \`--from <branch>\` (try \`--from ${DEFAULT_BRANCH}\`)`):ctx.source==="branch"?(fixes.push(`switch Branches first: \`fimo checkout ${DEFAULT_BRANCH}\``),fixes.push(`or pass \`--from ${DEFAULT_BRANCH}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--branch <existing>\` (try \`--branch ${DEFAULT_BRANCH}\`)`):fixes.push(`pass \`--from ${DEFAULT_BRANCH}\` to fork from main`),{ok:!1,message:`Cannot create Branch: parent Branch '${parentBranch}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentBranch,"validateParentBranch");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
|
|
1210
1210
|
Examples:
|
|
1211
1211
|
fimo integrations connect slack
|
|
@@ -1451,9 +1451,23 @@ Report: ${result.id}
|
|
|
1451
1451
|
Project: ${reportContext.projectName}
|
|
1452
1452
|
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(path49.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(`
|
|
1453
1453
|
`)}__name(buildSupportMessage,"buildSupportMessage");init_dist5();init_dist();init_api();init_auth();init_config();init_interactive();async function switchCommand(options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),orgs2=await new FimoApiClient(cfg).listOrganizations();if(orgs2.length===0){ui.error({command:"orgs switch",code:"NO_ORGANIZATIONS",message:"No organization found for this account."});return}if(options.org){let target2=orgs2.find(org=>org.id===options.org)??orgs2.find(org=>org.slug===options.org);if(!target2){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:`No organization matched "${options.org}".`,hint:"Run `fimo orgs list` to see available orgs."});return}setActiveOrganization({id:target2.id,name:target2.name,slug:target2.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target2.name}`,details:{id:target2.id,name:target2.name,slug:target2.slug}});return}assertInteractive("Pass --org <id-or-slug>.","orgs switch"),mt("Switch active organization");let currentId=creds.activeOrganization?.id,selected=await _t({message:"Select an organization",initialValue:currentId,options:orgs2.map(org=>({value:org.id,label:org.name,hint:org.id===currentId?"current":org.slug}))});if(q(selected)){ui.info({command:"orgs switch",message:"Cancelled."});return}let target=orgs2.find(org=>org.id===selected);if(!target){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:"Selected organization not found."});return}setActiveOrganization({id:target.id,name:target.name,slug:target.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target.name}`,details:{id:target.id,name:target.name,slug:target.slug}})}__name(switchCommand,"switchCommand");init_dist5();init_dist();import fs50 from"node:fs";import path51 from"node:path";init_git();init_interactive();init_project();init_scaffold_project();init_templates();import fs49 from"node:fs";import path50 from"node:path";function expectedFimoPackages(framework,usesReact){switch(framework){case"react-router":return["fimo","fimo-react","fimo-vite","fimo-react-router"];case"vite":return usesReact?["fimo","fimo-react","fimo-vite","fimo-react-router"]:["fimo","fimo-vite"];case"nextjs":return["fimo","fimo-react","fimo-next"];case"astro":return["fimo","fimo-astro"];case"sveltekit":return["fimo","fimo-sveltekit"];default:return["fimo"]}}__name(expectedFimoPackages,"expectedFimoPackages");var RETIRED_IMPORT_MAPPINGS=[{from:"fimo/ui",to:"fimo-react"},{from:"fimo/next",to:"fimo-next"},{from:"fimo/next/client",to:"fimo-next/client"},{from:"fimo/next/config",to:"fimo-next/config"},{from:"fimo/react-router",to:"fimo-react-router"},{from:"fimo/react-router/routes",to:"fimo-react-router/routes"},{from:"fimo/react-router/preset",to:"fimo-react-router/preset"},{from:"fimo/sveltekit",to:"fimo-sveltekit"},{from:"fimo/sveltekit/components",to:"fimo-sveltekit/components"},{from:"fimo/sveltekit/internal",to:"fimo-sveltekit/internal"},{from:"fimo/sveltekit/vite",to:"fimo-sveltekit/vite"},{from:"fimo/sveltekit/config",to:"fimo-sveltekit/config"},{from:"fimo/vite",to:{react:"fimo-react-router/vite",default:"fimo-vite"}}],MANUAL_REVIEW_IMPORTS=[{specifier:"fimo/astro/config",note:'fimo/astro/config stays valid for the provider-neutral Studio integration; only Fimo hosting for Astro moved to fimo-astro/config. Review astro.config.* and switch to `import { fimo } from "fimo-astro/config"` only if the project deploys through Fimo.'}];function migrationNote(...lines){return lines.join(`
|
|
1454
|
-
`)}__name(migrationNote,"migrationNote");var UPDATE_MIGRATIONS=[{version:"1.0.0",summary:"First stable release. The single fimo package splits into fimo plus per-framework companion packages, all released at the same version.",codemods:["retired-imports"],breakingChanges:[migrationNote("React components, React Router providers, and the Vite integration moved to framework packages. The update installs any missing packages before rewriting these imports.","","Before:","","```tsx","import { Label, Text } from 'fimo/ui';","import { FimoProviders } from 'fimo/react-router';","```","","After:","","```tsx","import { Label, Text } from 'fimo-react';","import { FimoProviders } from 'fimo-react-router';","```","","Update the Vite integration too:","","```ts","import { reactRouter } from '@react-router/dev/vite';","import { fimo } from 'fimo-react-router/vite';","import { defineConfig } from 'vite';","","export default defineConfig({"," plugins: [reactRouter(), fimo({ sitemap: true })],","});","```"),migrationNote("Next.js code moves from `fimo/next` to `fimo-next`. The update adds and installs `fimo-next` and `fimo-react` if they are missing, then rewrites the retired imports. Server and client imports remain separate.","","Before:","","```tsx","import { FimoProvider, getLabels } from 'fimo/next';","import { Text, useLabels } from 'fimo/next/client';","```","","After:","","```tsx","import { FimoProvider, getLabels } from 'fimo-next';","import { Text, useLabels } from 'fimo-next/client';","```","","Configure hosted previews through `fimo-next/config`:","","```ts","import type { NextConfig } from 'next';","import { withFimo } from 'fimo-next/config';","","const nextConfig: NextConfig = {};","","export default withFimo(nextConfig);","```"),migrationNote("Astro configuration depends on where the application is hosted, so the update reports `fimo/astro/config` for manual review instead of replacing it.","","For Fimo hosting or the Fimo server adapter:","","```js","import { fimo } from 'fimo-astro/config';","```","","For a static Astro project hosted elsewhere, keep:","","```js","import { fimo } from 'fimo/astro/config';","```","","Astro content APIs and components remain in `fimo`:","","```astro","---","import { getLabels } from 'fimo/astro';","import { Image, RichText, Text } from 'fimo/astro/components';","---","```"),migrationNote("SvelteKit integrations move from `fimo/sveltekit` to `fimo-sveltekit`. The update installs `fimo-sveltekit` if it is missing and rewrites the direct imports.","","Before:","","```ts","import { createFimo } from 'fimo/sveltekit';","import { fimo } from 'fimo/sveltekit/vite';","```","","After:","","```ts","import { createFimo } from 'fimo-sveltekit';","import { fimo } from 'fimo-sveltekit/vite';","```","","Update the root provider too:","","```svelte",'<script lang="ts">'," import { FimoProvider } from 'fimo-sveltekit/components';","</script>","```"),migrationNote("React Router projects using `fimo/react-router/routes` need a route-ownership migration after the compatibility import rewrite. Load the dedicated reference before changing the route configuration:","","```bash","npx fimo@latest skills get fimo-code --ref migrations/react-router-route-ownership","```")],improvements:[migrationNote("Framework code now has explicit import paths for each runtime:","","```ts","import { Text } from 'fimo-react'; // React components","import { getLabels } from 'fimo-next'; // Next.js server code","import { useLabels } from 'fimo-next/client'; // Next.js client code","import { createFimo } from 'fimo-sveltekit'; // SvelteKit server code","```"),"`fimo update` handles package additions and direct import rewrites. It leaves conditional migrations, including Astro hosting and React Router route ownership, as explicit manual steps."],recommendations:[migrationNote("Keep `fimo validate --json` at the beginning of the existing build command:","","```json","{",' "scripts": {',' "build": "fimo validate --json && vite build"'," }","}","```","","Preserve the framework build command. For example, use `next build` for Next.js and `astro build` for Astro."),migrationNote("Record the exact package-manager version and commit its lockfile:","","```json","{",' "packageManager": "pnpm@10.26.0"',"}","```"),migrationNote("Load the detected framework reference before completing manual changes, then run the project build:","","```bash","npx fimo@latest skills get fimo-code --ref frameworks/next","npx fimo@latest skills get fimo-code --ref frameworks/astro","npx fimo@latest skills get fimo-code --ref frameworks/sveltekit","npx fimo@latest skills get fimo-code --ref frameworks/react-router","npx fimo@latest skills get fimo-code --ref frameworks/vite-react","pnpm build","```")]}];function migrationsForTarget(target){return UPDATE_MIGRATIONS.filter(entry=>compareVersions(entry.version,target)<=0)}__name(migrationsForTarget,"migrationsForTarget");function updateGuidanceCommand(){return"npx fimo@latest skills get fimo-cli --ref update"}__name(updateGuidanceCommand,"updateGuidanceCommand");var EXACT_VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function compareVersions(a,b){let parse15=__name(value=>value.split("-")[0].split(".").map(Number),"parse"),[aMajor,aMinor,aPatch]=parse15(a),[bMajor,bMinor,bPatch]=parse15(b);return aMajor-bMajor||aMinor-bMinor||aPatch-bPatch}__name(compareVersions,"compareVersions");var OWNED_DIST_TAGS=new Set(["latest","staging","experimental"]);function classifyDepValue(value){return value.startsWith("file:")||/r2\.dev\/cli\//.test(value)||value.endsWith(".tgz")?"dev-pin":/^[\^~]?\d+\.\d+\.\d+/.test(value)||OWNED_DIST_TAGS.has(value)?"owned":"bespoke"}__name(classifyDepValue,"classifyDepValue");function planPackageChanges(pkg,target,expected){let changes=[],blockers=[],declared=new Set,fimoSection=null;for(let section2 of["dependencies","devDependencies"]){let deps=pkg[section2];if(deps)for(let name of FIMO_PACKAGES){let current=deps[name];if(typeof current!="string")continue;declared.add(name),name==="fimo"&&fimoSection===null&&(fimoSection=section2);let targetPin=deriveFimoPackagePin(name,target),kind=classifyDepValue(current);if(kind!=="owned"){let reason=kind==="dev-pin"?`"${current}" selects a development build; \`fimo update\` never replaces it. Publish and repin through the development channel, or set an exact version yourself first.`:`"${current}" is not a version this CLI manages; update it yourself first.`;changes.push({name,section:section2,from:current,to:null,action:"blocked",reason}),blockers.push({code:kind==="dev-pin"?"DEV_PIN":"BESPOKE_PIN",message:`${section2}.${name}: ${reason}`});continue}if(current===targetPin){changes.push({name,section:section2,from:current,to:current,action:"unchanged"});continue}changes.push({name,section:section2,from:current,to:targetPin,action:"update"})}}for(let name of expected)declared.has(name)||changes.push({name,section:fimoSection??"dependencies",from:null,to:deriveFimoPackagePin(name,target),action:"add"});return{changes,blockers}}__name(planPackageChanges,"planPackageChanges");function applyPackageChanges(pkg,changes){let changed=!1;for(let change of changes){if(change.action!=="update"&&change.action!=="add"||change.to===null)continue;let deps=pkg[change.section]??={};deps[change.name]!==change.to&&(deps[change.name]=change.to,changed=!0)}return changed}__name(applyPackageChanges,"applyPackageChanges");var KNOWN_FRAMEWORKS=["react-router","vite","astro","nextjs","sveltekit"],COMPANION_FRAMEWORKS=[["fimo-react-router","react-router"],["fimo-next","nextjs"],["fimo-sveltekit","sveltekit"],["fimo-astro","astro"],["fimo-vite","vite"]];function resolveUpdateFramework(detectedSlug,pkg){let deps={...pkg.dependencies,...pkg.devDependencies},has2=__name(name=>typeof deps[name]=="string","has"),framework=KNOWN_FRAMEWORKS.find(slug=>slug===detectedSlug)??null;framework||(framework=COMPANION_FRAMEWORKS.find(([companion])=>has2(companion))?.[1]??null);let usesReact=framework==="react-router"||framework==="nextjs"||has2("react")||has2("fimo-react");return{framework,usesReact,label:framework==="vite"?usesReact?"vite (react)":"vite":framework??"unknown"}}__name(resolveUpdateFramework,"resolveUpdateFramework");var SKIPPED_DIRECTORIES=new Set(["node_modules","dist","build","out","coverage","vendor"]),SOURCE_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".svelte",".astro",".vue",".mdx"]),MAX_FILE_BYTES=1024*1024;function escapeRegExp2(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp2,"escapeRegExp");function replacementFor(mapping,usesReact){return typeof mapping.to=="string"?mapping.to:usesReact?mapping.to.react:mapping.to.default}__name(replacementFor,"replacementFor");function listSourceFiles(root2){let files=[],walk=__name(dir=>{let entries2;try{entries2=fs49.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(entry.isDirectory()){!entry.name.startsWith(".")&&!SKIPPED_DIRECTORIES.has(entry.name)&&walk(path50.join(dir,entry.name));continue}entry.isFile()&&SOURCE_EXTENSIONS.has(path50.extname(entry.name))&&files.push(path50.join(dir,entry.name))}},"walk");return walk(root2),files.sort()}__name(listSourceFiles,"listSourceFiles");function runRetiredImportsCodemod(options){let{cwd,usesReact,write}=options,changedFiles=[],manualFollowUps=[],files=listSourceFiles(cwd),mappings=[...RETIRED_IMPORT_MAPPINGS].sort((a,b)=>b.from.length-a.from.length);for(let filePath of files){let source;try{if(fs49.statSync(filePath).size>MAX_FILE_BYTES)continue;source=fs49.readFileSync(filePath,"utf8")}catch{continue}if(!source.includes("fimo/"))continue;let relative3=path50.relative(cwd,filePath)||filePath,updated=source,replacements=[];for(let mapping of mappings){let to=replacementFor(mapping,usesReact),pattern=new RegExp(`(['"])${escapeRegExp2(mapping.from)}\\1`,"g"),count=0;updated=updated.replace(pattern,(_match,quote2)=>(count+=1,`${quote2}${to}${quote2}`)),count>0&&replacements.push({from:mapping.from,to,count}),updated.includes(`\`${mapping.from}\``)&&manualFollowUps.push({file:relative3,specifier:mapping.from,note:`Found \`${mapping.from}\` in a template literal; replace it with \`${to}\` manually.`})}for(let manual of MANUAL_REVIEW_IMPORTS)new RegExp(`['"\`]${escapeRegExp2(manual.specifier)}['"\`]`).test(updated)&&manualFollowUps.push({file:relative3,specifier:manual.specifier,note:manual.note});replacements.length>0&&(changedFiles.push({file:relative3,replacements}),write&&fs49.writeFileSync(filePath,updated))}return{id:"retired-imports",filesScanned:files.length,changedFiles,manualFollowUps}}__name(runRetiredImportsCodemod,"runRetiredImportsCodemod");async function updateCommand3(version,options){let target=version.trim().replace(/^v/,"");if(!EXACT_VERSION_PATTERN.test(target)){ui.error({command:"update",code:"UPDATE_TARGET_INVALID",message:`"${version}" is not an exact version.`,hint:"Pass the exact release to update to, for example `fimo update 1.0.0`. Ranges and dist-tags are not accepted."});return}let cwd=resolveProjectCwd(options.cwd),packagePath=path51.join(cwd,"package.json"),pkg;try{pkg=JSON.parse(fs50.readFileSync(packagePath,"utf8"))}catch{ui.error({command:"update",code:"UPDATE_NO_FIMO_DEP",message:`No readable package.json at ${packagePath}.`,hint:"Run `fimo update` from a project directory (or pass -C <dir>)."});return}let declaredFimo=pkg.dependencies?.fimo??pkg.devDependencies?.fimo??null;if(typeof declaredFimo!="string"){ui.error({command:"update",code:"UPDATE_NO_FIMO_DEP",message:"This project does not declare a `fimo` dependency.",hint:"`fimo update` updates a project that already uses Fimo. Use `fimo init` or `fimo link` to set one up."});return}let detected=await detectProjectFramework(cwd).catch(()=>null),framework=resolveUpdateFramework(detected?.slug??null,pkg),expected=expectedFimoPackages(framework.framework,framework.usesReact),{changes,blockers}=planPackageChanges(pkg,target,expected),inRepo=await isGitRepo(cwd);inRepo&&await hasUncommittedChanges(cwd)&&options.allowDirty!==!0&&blockers.push({code:"DIRTY_WORKTREE",message:"The working tree has uncommitted changes. Commit or stash them so the update lands as its own reviewable change, or pass --allow-dirty."});let migrations=migrationsForTarget(target),runsRetiredImports=migrations.some(entry=>entry.codemods.includes("retired-imports")),codemodPreview=runsRetiredImports?runRetiredImportsCodemod({cwd,usesReact:framework.usesReact,write:!1}):null,manualSteps=[];if(inRepo||manualSteps.push("Not a git checkout \u2014 review and version the changes yourself after the update."),codemodPreview)for(let followUp of codemodPreview.manualFollowUps)manualSteps.push(`${followUp.file}: ${followUp.note}`);manualSteps.push("Run the project dev or build script afterwards to confirm the app still works.");let recommendations=migrations.flatMap(entry=>[...entry.recommendations]);if(migrations.length===0){let newest=UPDATE_MIGRATIONS.at(-1);recommendations.push(`No bundled migration notes cover ${target}${newest?` (newest known release notes: ${newest.version})`:""}; only dependency pinning applies.`)}let report={from:{declared:declaredFimo,installed:readInstalledFimoVersion(cwd)},to:target,framework:{name:framework.framework,label:framework.label,usesReact:framework.usesReact},mode:"plan",applied:!1,packages:changes,blockers,breakingChanges:migrations.flatMap(entry=>[...entry.breakingChanges]),improvements:migrations.flatMap(entry=>[...entry.improvements]),recommendations,manualSteps,codemods:codemodPreview?[codemodPreview]:[],install:{status:"skipped",packageManager:null,reason:"not applied"},validation:{status:"skipped",reason:"not applied",errors:0},guidance:{reference:"fimo skills get fimo-cli --ref update",command:updateGuidanceCommand()}};if(options.dryRun===!0){report.mode="dry-run",emitReport(report);return}if((currentMode().format==="json"||!isInteractive())&&options.apply!==!0){emitReport(report,"Nothing was written. Re-run with --apply to update the project.");return}if(blockers.length>0){let dirtyOnly=blockers.every(blocker=>blocker.code==="DIRTY_WORKTREE");ui.error({command:"update",code:dirtyOnly?"UPDATE_DIRTY_WORKTREE":"UPDATE_BLOCKED",message:blockers.map(blocker=>blocker.message).join(`
|
|
1454
|
+
`)}__name(migrationNote,"migrationNote");var UPDATE_MIGRATIONS=[{version:"1.0.0",summary:"First stable release. The single fimo package splits into fimo plus per-framework companion packages, all released at the same version.",codemods:["retired-imports"],breakingChanges:[migrationNote("React components, React Router providers, and the Vite integration moved to framework packages. The update installs any missing packages before rewriting these imports.","","Before:","","```tsx","import { Label, Text } from 'fimo/ui';","import { FimoProviders } from 'fimo/react-router';","```","","After:","","```tsx","import { Label, Text } from 'fimo-react';","import { FimoProviders } from 'fimo-react-router';","```","","Update the Vite integration too:","","```ts","import { reactRouter } from '@react-router/dev/vite';","import { fimo } from 'fimo-react-router/vite';","import { defineConfig } from 'vite';","","export default defineConfig({"," plugins: [reactRouter(), fimo({ sitemap: true })],","});","```"),migrationNote("Next.js code moves from `fimo/next` to `fimo-next`. The update adds and installs `fimo-next` and `fimo-react` if they are missing, then rewrites the retired imports. Server and client imports remain separate.","","Before:","","```tsx","import { FimoProvider, getLabels } from 'fimo/next';","import { Text, useLabels } from 'fimo/next/client';","```","","After:","","```tsx","import { FimoProvider, getLabels } from 'fimo-next';","import { Text, useLabels } from 'fimo-next/client';","```","","Configure hosted previews through `fimo-next/config`:","","```ts","import type { NextConfig } from 'next';","import { withFimo } from 'fimo-next/config';","","const nextConfig: NextConfig = {};","","export default withFimo(nextConfig);","```"),migrationNote("Astro configuration depends on where the application is hosted, so the update reports `fimo/astro/config` for manual review instead of replacing it.","","For Fimo hosting or the Fimo server adapter:","","```js","import { fimo } from 'fimo-astro/config';","```","","For a static Astro project hosted elsewhere, keep:","","```js","import { fimo } from 'fimo/astro/config';","```","","Astro content APIs and components remain in `fimo`:","","```astro","---","import { getLabels } from 'fimo/astro';","import { Image, RichText, Text } from 'fimo/astro/components';","---","```"),migrationNote("SvelteKit integrations move from `fimo/sveltekit` to `fimo-sveltekit`. The update installs `fimo-sveltekit` if it is missing and rewrites the direct imports.","","Before:","","```ts","import { createFimo } from 'fimo/sveltekit';","import { fimo } from 'fimo/sveltekit/vite';","```","","After:","","```ts","import { createFimo } from 'fimo-sveltekit';","import { fimo } from 'fimo-sveltekit/vite';","```","","Update the root provider too:","","```svelte",'<script lang="ts">'," import { FimoProvider } from 'fimo-sveltekit/components';","</script>","```"),migrationNote("React Router projects using `fimo/react-router/routes` need a route-ownership migration after the compatibility import rewrite. Load the dedicated reference before changing the route configuration:","","```bash","npx fimo@latest skills get fimo-code --ref migrations/react-router-route-ownership","```")],improvements:[migrationNote("Framework code now has explicit import paths for each runtime:","","```ts","import { Text } from 'fimo-react'; // React components","import { getLabels } from 'fimo-next'; // Next.js server code","import { useLabels } from 'fimo-next/client'; // Next.js client code","import { createFimo } from 'fimo-sveltekit'; // SvelteKit server code","```"),"`fimo update` handles package additions and direct import rewrites. It leaves conditional migrations, including Astro hosting and React Router route ownership, as explicit manual steps."],recommendations:[migrationNote("Keep `fimo validate --json` at the beginning of the existing build command:","","```json","{",' "scripts": {',' "build": "fimo validate --json && vite build"'," }","}","```","","Preserve the framework build command. For example, use `next build` for Next.js and `astro build` for Astro."),migrationNote("Record the exact package-manager version and commit its lockfile:","","```json","{",' "packageManager": "pnpm@10.26.0"',"}","```"),migrationNote("Load the detected framework reference before completing manual changes, then run the project build:","","```bash","npx fimo@latest skills get fimo-code --ref frameworks/next","npx fimo@latest skills get fimo-code --ref frameworks/astro","npx fimo@latest skills get fimo-code --ref frameworks/sveltekit","npx fimo@latest skills get fimo-code --ref frameworks/react-router","npx fimo@latest skills get fimo-code --ref frameworks/vite-react","pnpm build","```")]},{version:"2.2.0",summary:"Media fields store asset references and load current asset facts only when a read requests them.",codemods:[],breakingChanges:[],improvements:[migrationNote("Media metadata is opt-in.","","Without `populate`:","","```ts","const article = await Article.getBySlug('hello');","// article.cover:","// { id?: string; url: string; alt?: string }","```","","Add `populate` when this read needs asset metadata:","","```ts","const article = await Article.getBySlug('hello', { populate: ['cover'] as const });","// article.cover:","// { id?: string; url: string; alt?: string; name?: string; mime?: string; width?: number; height?: number }","```","","Lists use the same option:","","```ts","const page = await Article.list({ populate: ['cover'] as const });","// page.items[0].cover has the populated shape above","```","","The fields marked `?` may be missing for external, missing, or incomplete assets."),migrationNote("Writes keep the reference and optional entry alt text:","","```ts","await Article.create({ cover: { id: 'asset_123', alt: 'Hero' } });","```","","Do not write asset metadata; Fimo reads it when you populate.")],recommendations:["Add `populate` only to reads that use current media metadata. Leave other reads unchanged."]}];function migrationsForTarget(target){return UPDATE_MIGRATIONS.filter(entry=>compareVersions(entry.version,target)<=0)}__name(migrationsForTarget,"migrationsForTarget");function updateGuidanceCommand(){return"npx fimo@latest skills get fimo-cli --ref update"}__name(updateGuidanceCommand,"updateGuidanceCommand");var EXACT_VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function compareVersions(a,b){let parse15=__name(value=>value.split("-")[0].split(".").map(Number),"parse"),[aMajor,aMinor,aPatch]=parse15(a),[bMajor,bMinor,bPatch]=parse15(b);return aMajor-bMajor||aMinor-bMinor||aPatch-bPatch}__name(compareVersions,"compareVersions");var OWNED_DIST_TAGS=new Set(["latest","staging","experimental"]);function classifyDepValue(value){return value.startsWith("file:")||/r2\.dev\/cli\//.test(value)||value.endsWith(".tgz")?"dev-pin":/^[\^~]?\d+\.\d+\.\d+/.test(value)||OWNED_DIST_TAGS.has(value)?"owned":"bespoke"}__name(classifyDepValue,"classifyDepValue");function planPackageChanges(pkg,target,expected){let changes=[],blockers=[],declared=new Set,fimoSection=null;for(let section2 of["dependencies","devDependencies"]){let deps=pkg[section2];if(deps)for(let name of FIMO_PACKAGES){let current=deps[name];if(typeof current!="string")continue;declared.add(name),name==="fimo"&&fimoSection===null&&(fimoSection=section2);let targetPin=deriveFimoPackagePin(name,target),kind=classifyDepValue(current);if(kind!=="owned"){let reason=kind==="dev-pin"?`"${current}" selects a development build; \`fimo update\` never replaces it. Publish and repin through the development channel, or set an exact version yourself first.`:`"${current}" is not a version this CLI manages; update it yourself first.`;changes.push({name,section:section2,from:current,to:null,action:"blocked",reason}),blockers.push({code:kind==="dev-pin"?"DEV_PIN":"BESPOKE_PIN",message:`${section2}.${name}: ${reason}`});continue}if(current===targetPin){changes.push({name,section:section2,from:current,to:current,action:"unchanged"});continue}changes.push({name,section:section2,from:current,to:targetPin,action:"update"})}}for(let name of expected)declared.has(name)||changes.push({name,section:fimoSection??"dependencies",from:null,to:deriveFimoPackagePin(name,target),action:"add"});return{changes,blockers}}__name(planPackageChanges,"planPackageChanges");function applyPackageChanges(pkg,changes){let changed=!1;for(let change of changes){if(change.action!=="update"&&change.action!=="add"||change.to===null)continue;let deps=pkg[change.section]??={};deps[change.name]!==change.to&&(deps[change.name]=change.to,changed=!0)}return changed}__name(applyPackageChanges,"applyPackageChanges");var KNOWN_FRAMEWORKS=["react-router","vite","astro","nextjs","sveltekit"],COMPANION_FRAMEWORKS=[["fimo-react-router","react-router"],["fimo-next","nextjs"],["fimo-sveltekit","sveltekit"],["fimo-astro","astro"],["fimo-vite","vite"]];function resolveUpdateFramework(detectedSlug,pkg){let deps={...pkg.dependencies,...pkg.devDependencies},has2=__name(name=>typeof deps[name]=="string","has"),framework=KNOWN_FRAMEWORKS.find(slug=>slug===detectedSlug)??null;framework||(framework=COMPANION_FRAMEWORKS.find(([companion])=>has2(companion))?.[1]??null);let usesReact=framework==="react-router"||framework==="nextjs"||has2("react")||has2("fimo-react");return{framework,usesReact,label:framework==="vite"?usesReact?"vite (react)":"vite":framework??"unknown"}}__name(resolveUpdateFramework,"resolveUpdateFramework");var SKIPPED_DIRECTORIES=new Set(["node_modules","dist","build","out","coverage","vendor"]),SOURCE_EXTENSIONS=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".svelte",".astro",".vue",".mdx"]),MAX_FILE_BYTES=1024*1024;function escapeRegExp2(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp2,"escapeRegExp");function replacementFor(mapping,usesReact){return typeof mapping.to=="string"?mapping.to:usesReact?mapping.to.react:mapping.to.default}__name(replacementFor,"replacementFor");function listSourceFiles(root2){let files=[],walk=__name(dir=>{let entries2;try{entries2=fs49.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(entry.isDirectory()){!entry.name.startsWith(".")&&!SKIPPED_DIRECTORIES.has(entry.name)&&walk(path50.join(dir,entry.name));continue}entry.isFile()&&SOURCE_EXTENSIONS.has(path50.extname(entry.name))&&files.push(path50.join(dir,entry.name))}},"walk");return walk(root2),files.sort()}__name(listSourceFiles,"listSourceFiles");function runRetiredImportsCodemod(options){let{cwd,usesReact,write}=options,changedFiles=[],manualFollowUps=[],files=listSourceFiles(cwd),mappings=[...RETIRED_IMPORT_MAPPINGS].sort((a,b)=>b.from.length-a.from.length);for(let filePath of files){let source;try{if(fs49.statSync(filePath).size>MAX_FILE_BYTES)continue;source=fs49.readFileSync(filePath,"utf8")}catch{continue}if(!source.includes("fimo/"))continue;let relative3=path50.relative(cwd,filePath)||filePath,updated=source,replacements=[];for(let mapping of mappings){let to=replacementFor(mapping,usesReact),pattern=new RegExp(`(['"])${escapeRegExp2(mapping.from)}\\1`,"g"),count=0;updated=updated.replace(pattern,(_match,quote2)=>(count+=1,`${quote2}${to}${quote2}`)),count>0&&replacements.push({from:mapping.from,to,count}),updated.includes(`\`${mapping.from}\``)&&manualFollowUps.push({file:relative3,specifier:mapping.from,note:`Found \`${mapping.from}\` in a template literal; replace it with \`${to}\` manually.`})}for(let manual of MANUAL_REVIEW_IMPORTS)new RegExp(`['"\`]${escapeRegExp2(manual.specifier)}['"\`]`).test(updated)&&manualFollowUps.push({file:relative3,specifier:manual.specifier,note:manual.note});replacements.length>0&&(changedFiles.push({file:relative3,replacements}),write&&fs49.writeFileSync(filePath,updated))}return{id:"retired-imports",filesScanned:files.length,changedFiles,manualFollowUps}}__name(runRetiredImportsCodemod,"runRetiredImportsCodemod");function renderMigrationGuidance(migration){return[migration.breakingChanges.length>0?`### Breaking changes
|
|
1455
|
+
|
|
1456
|
+
${migration.breakingChanges.join(`
|
|
1457
|
+
|
|
1458
|
+
`)}`:null,migration.improvements.length>0?`### Improvements
|
|
1459
|
+
|
|
1460
|
+
${migration.improvements.join(`
|
|
1461
|
+
|
|
1462
|
+
`)}`:null,migration.recommendations.length>0?`### Recommendations
|
|
1463
|
+
|
|
1464
|
+
${migration.recommendations.join(`
|
|
1465
|
+
|
|
1466
|
+
`)}`:null].filter(section2=>section2!==null).join(`
|
|
1467
|
+
|
|
1468
|
+
`)}__name(renderMigrationGuidance,"renderMigrationGuidance");function buildMigrationReports(migrations,codemodPreview){return migrations.map(migration=>({version:migration.version,summary:migration.summary,migrate:renderMigrationGuidance(migration),codemods:codemodPreview&&migration.codemods.includes(codemodPreview.id)?[codemodPreview]:[]}))}__name(buildMigrationReports,"buildMigrationReports");function replaceMigrationCodemod(reports,codemodResult){if(codemodResult)for(let migration of reports)migration.codemods=migration.codemods.map(codemod=>codemod.id===codemodResult.id?codemodResult:codemod)}__name(replaceMigrationCodemod,"replaceMigrationCodemod");async function updateCommand3(version,options){let target=version.trim().replace(/^v/,"");if(!EXACT_VERSION_PATTERN.test(target)){ui.error({command:"update",code:"UPDATE_TARGET_INVALID",message:`"${version}" is not an exact version.`,hint:"Pass the exact release to update to, for example `fimo update 1.0.0`. Ranges and dist-tags are not accepted."});return}let cwd=resolveProjectCwd(options.cwd),packagePath=path51.join(cwd,"package.json"),pkg;try{pkg=JSON.parse(fs50.readFileSync(packagePath,"utf8"))}catch{ui.error({command:"update",code:"UPDATE_NO_FIMO_DEP",message:`No readable package.json at ${packagePath}.`,hint:"Run `fimo update` from a project directory (or pass -C <dir>)."});return}let declaredFimo=pkg.dependencies?.fimo??pkg.devDependencies?.fimo??null;if(typeof declaredFimo!="string"){ui.error({command:"update",code:"UPDATE_NO_FIMO_DEP",message:"This project does not declare a `fimo` dependency.",hint:"`fimo update` updates a project that already uses Fimo. Use `fimo init` or `fimo link` to set one up."});return}let detected=await detectProjectFramework(cwd).catch(()=>null),framework=resolveUpdateFramework(detected?.slug??null,pkg),expected=expectedFimoPackages(framework.framework,framework.usesReact),{changes,blockers}=planPackageChanges(pkg,target,expected),inRepo=await isGitRepo(cwd);inRepo&&await hasUncommittedChanges(cwd)&&options.allowDirty!==!0&&blockers.push({code:"DIRTY_WORKTREE",message:"The working tree has uncommitted changes. Commit or stash them so the update lands as its own reviewable change, or pass --allow-dirty."});let migrations=migrationsForTarget(target),runsRetiredImports=migrations.some(entry=>entry.codemods.includes("retired-imports")),codemodPreview=runsRetiredImports?runRetiredImportsCodemod({cwd,usesReact:framework.usesReact,write:!1}):null,manualSteps=[];if(inRepo||manualSteps.push("Not a git checkout \u2014 review and version the changes yourself after the update."),codemodPreview)for(let followUp of codemodPreview.manualFollowUps)manualSteps.push(`${followUp.file}: ${followUp.note}`);if(manualSteps.push("Run the project dev or build script afterwards to confirm the app still works."),migrations.length===0){let newest=UPDATE_MIGRATIONS.at(-1);manualSteps.push(`No bundled migration notes cover ${target}${newest?` (newest known release notes: ${newest.version})`:""}; only dependency pinning applies.`)}let report={from:{declared:declaredFimo,installed:readInstalledFimoVersion(cwd)},to:target,framework:{name:framework.framework,label:framework.label,usesReact:framework.usesReact},mode:"plan",applied:!1,packages:changes,blockers,migrations:buildMigrationReports(migrations,codemodPreview),manualSteps,install:{status:"skipped",packageManager:null,reason:"not applied"},validation:{status:"skipped",reason:"not applied",errors:0},guidance:{reference:"fimo skills get fimo-cli --ref update",command:updateGuidanceCommand()}};if(options.dryRun===!0){report.mode="dry-run",emitReport(report);return}if((currentMode().format==="json"||!isInteractive())&&options.apply!==!0){emitReport(report,"Nothing was written. Re-run with --apply to update the project.");return}if(blockers.length>0){let dirtyOnly=blockers.every(blocker=>blocker.code==="DIRTY_WORKTREE");ui.error({command:"update",code:dirtyOnly?"UPDATE_DIRTY_WORKTREE":"UPDATE_BLOCKED",message:blockers.map(blocker=>blocker.message).join(`
|
|
1455
1469
|
`),hint:dirtyOnly?"Commit or stash first, or re-run with --allow-dirty. Use --dry-run to inspect the plan.":"Resolve the pins above, or use --dry-run to inspect the full plan."});return}if(options.apply!==!0){wt(renderUpdateReport(report),`fimo update ${target}`);let answer=await ot2({message:`Apply these changes and update to fimo@${target}?`});if(q(answer)||answer!==!0){ui.error({command:"update",code:"UPDATE_CANCELLED",message:"Update cancelled \u2014 nothing was written."});return}}report.mode="apply",applyPackageChanges(pkg,changes)&&fs50.writeFileSync(packagePath,`${JSON.stringify(pkg,null,2)}
|
|
1456
|
-
`);let codemodResult=runsRetiredImports?runRetiredImportsCodemod({cwd,usesReact:framework.usesReact,write:!0}):null;report.
|
|
1470
|
+
`);let codemodResult=runsRetiredImports?runRetiredImportsCodemod({cwd,usesReact:framework.usesReact,write:!0}):null;replaceMigrationCodemod(report.migrations,codemodResult),report.applied=!0,report.install=await runInstall(cwd,options),report.validation=await runValidation(cwd,options,report.install.status);let hint;report.install.status==="failed"?(hint="Dependency installation failed \u2014 fix the install, then re-run `fimo validate`.",process.exitCode=1):report.validation.status==="failed"&&(hint="Validation failed after the update \u2014 fix the reported errors, then re-run `fimo validate`.",process.exitCode=1),emitReport(report,hint)}__name(updateCommand3,"updateCommand");function readInstalledFimoVersion(cwd){try{let installed=JSON.parse(fs50.readFileSync(path51.join(cwd,"node_modules","fimo","package.json"),"utf8"));return typeof installed.version=="string"?installed.version:null}catch{return null}}__name(readInstalledFimoVersion,"readInstalledFimoVersion");async function runInstall(cwd,options){if(options.install===!1)return{status:"skipped",packageManager:null,reason:"--no-install"};let contract=await resolvePackageManagerContract(cwd),manager=null;if(contract.status==="declared"?manager=contract.packageManager.split("@")[0]:contract.status==="inferred"&&(manager=contract.manager),!manager)return{status:"skipped",packageManager:null,reason:contract.status==="unresolved"?contract.message:"No package-manager signal in this directory; run the install yourself."};let result=await installDependencies(manager,cwd);return{status:result.installed?"installed":"failed",packageManager:manager,reason:result.error}}__name(runInstall,"runInstall");async function runValidation(cwd,options,installStatus){if(options.validate===!1)return{status:"skipped",reason:"--no-validate",errors:0};if(installStatus==="failed")return{status:"skipped",reason:"dependency installation failed",errors:0};try{let result=await runValidate({cwd}),errors=Object.values(result.phases).reduce((total,phase)=>total+phase.errors.length,0);return result.ok?{status:"passed",reason:null,errors:0}:{status:"failed",reason:"fimo validate reported errors \u2014 run `fimo validate` for details",errors}}catch(error){return{status:"failed",reason:`fimo validate could not run: ${error instanceof Error?error.message:String(error)}`,errors:0}}}__name(runValidation,"runValidation");function emitReport(report,hint){ui.result({command:"update",data:report,render:__name(()=>renderUpdateReport(report),"render"),...hint?{hint}:{}})}__name(emitReport,"emitReport");function section(title,lines){return lines.length===0?[]:["",`${title}:`,...lines.map(line=>` - ${line}`)]}__name(section,"section");function renderUpdateReport(report){let lines=[],fromLabel=report.from.installed?`${report.from.declared} (installed ${report.from.installed})`:`${report.from.declared}`;lines.push(`Update fimo ${fromLabel} -> ${report.to}`),lines.push(`Framework: ${report.framework.label}`);let packageLines=report.packages.filter(change=>change.action!=="unchanged").map(change=>change.action==="add"?`${change.name}: add ${change.to} (${change.section})`:change.action==="blocked"?`${change.name}: kept at ${change.from} \u2014 ${change.reason??"blocked"}`:`${change.name}: ${change.from} -> ${change.to}`);lines.push(...section("Packages",packageLines.length>0?packageLines:["already up to date"]));for(let migration of report.migrations){lines.push("",`Migration ${migration.version}: ${migration.summary}`),migration.migrate&&lines.push("",migration.migrate);for(let codemod of migration.codemods){let changeLines=codemod.changedFiles.map(file=>{let detail=file.replacements.map(r=>`${r.from} -> ${r.to} (${r.count})`).join(", ");return`${file.file}: ${detail}`});lines.push(...section(`Codemod ${codemod.id} (${codemod.filesScanned} files scanned)`,changeLines.length>0?changeLines:["no retired imports found"]))}}if(lines.push(...section("Blockers",report.blockers.map(blocker=>blocker.message))),lines.push(...section("Manual steps",report.manualSteps)),report.mode==="apply"){let installLine=report.install.status==="installed"?`installed with ${report.install.packageManager}`:`${report.install.status}${report.install.reason?` (${report.install.reason})`:""}`,validationLine=report.validation.status==="failed"?`failed${report.validation.errors>0?` (${report.validation.errors} errors)`:""}${report.validation.reason?` \u2014 ${report.validation.reason}`:""}`:`${report.validation.status}${report.validation.reason?` (${report.validation.reason})`:""}`;lines.push("",`Install: ${installLine}`,`Validation: ${validationLine}`)}else lines.push("",report.mode==="dry-run"?"Dry run \u2014 nothing was written.":"Plan only \u2014 nothing was written.");return lines.push("",`Detailed guidance: ${report.guidance.command}`),lines.join(`
|
|
1457
1471
|
`)}__name(renderUpdateReport,"renderUpdateReport");init_esm();init_dist();init_api();init_config();import{readFile as readFile6}from"node:fs/promises";import{resolve as resolve9}from"node:path";init_project_context();init_project();var WebhookCommandError=class extends Error{static{__name(this,"WebhookCommandError")}code;constructor(code2,message){super(message),this.name="WebhookCommandError",this.code=code2}};function addScopeOptions4(command){return command.option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions4,"addScopeOptions");function collect4(value,previous){return[...previous??[],value]}__name(collect4,"collect");function registerWebhooksCommands(program2){let webhooks=program2.command("webhooks").description("Manage outbound project webhooks").addHelpText("after",`
|
|
1458
1472
|
Examples:
|
|
1459
1473
|
fimo webhooks events
|
|
@@ -1467,10 +1481,10 @@ Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=lite
|
|
|
1467
1481
|
`);addScopeOptions4(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions4(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand5(opts,command)),addScopeOptions4(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect4).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id","main").option("--debounce-changes <immediate|5s|30s|1m>","Combine rapid entry.changed events into one delivery").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand4(name,opts,command)),addScopeOptions4(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect4).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id").option("--debounce-changes <immediate|5s|30s|1m>","Change the entry.changed debounce window").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand4(webhookId,opts,command)),addScopeOptions4(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions4(addPaginationOptions(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries"),{defaultLimit:50,maxLimit:100})).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope4(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,branch:ctx.branch}}return await requireOperation(op,scope),{...scope,api:new FimoApiClient(loadConfig())}}__name(resolveScope4,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope4("webhooks.events",opts,command),events=await api.listWebhookEvents(projectId);if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand5(opts,command){let{api,projectId}=await resolveScope4("webhooks.list",opts,command),webhooks=await api.listProjectWebhooks(projectId);ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand5,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.get",opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand4(name,opts,command){let{api,projectId}=await resolveScope4("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1,entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges??(opts.event==="entry.changed"?"5s":"immediate"))});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await api.createProjectWebhook(projectId,parsed.data);renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand4,"createCommand");async function updateCommand4(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await api.getProjectWebhook(projectId,webhookId),filter4=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter4?{filter:filter4}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{},...opts.debounceChanges!==void 0?{entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges)}:opts.event==="entry.changed"&¤t.eventType!=="entry.changed"?{entryBatchWindowSeconds:5}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await api.updateProjectWebhook(projectId,webhookId,parsed.data))}__name(updateCommand4,"updateCommand");async function deleteCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.delete",opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand3,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.test",opts,command),data2=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await api.testProjectWebhook(projectId,webhookId,{data:data2});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await api.getProjectWebhookDelivery(projectId,webhookId,delivery.id)).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let pagination;try{pagination=parsePaginationOptions(opts,{defaultLimit:50,maxLimit:100}),pagination.cursor!==void 0&&parseCursorNumber(pagination.cursor,{defaultValue:1,minimum:1})}catch(error){throw error instanceof PaginationValidationError?new WebhookCommandError(error.kind==="invalid_limit"?"WEBHOOK_LIMIT_INVALID":"WEBHOOK_CURSOR_INVALID",error.message):error}let{api,projectId}=await resolveScope4("webhooks.deliveries.list",opts,command),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let pageNumber=parseCursorNumber(cursor,{defaultValue:1,minimum:1}),response=await api.listProjectWebhookDeliveries(projectId,webhookId,{page:pageNumber,limit:pagination.limit});return{items:response.items,nextCursor:response.pagination.hasMore?String(response.pagination.page+1):null,total:response.pagination.total,pagination:response.pagination,stats:response.stats}},"fetchPage")}),trailingArgs=[];opts.project&&trailingArgs.push("--project",opts.project),opts.cwd&&trailingArgs.push("--cwd",opts.cwd);let rows=page.items.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)})),hint=page.nextCursor?buildPaginationHint(["fimo","webhooks","deliveries",webhookId],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs}):void 0;ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows,jsonData:{items:page.items,nextCursor:page.nextCursor,total:page.total,pagination:page.pagination,stats:page.stats},...hint?{hint}:{}})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await api.getProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.rotate_secret",opts,command),signingSecret=await api.rotateProjectWebhookSecret(projectId,webhookId);renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function parseEntryBatchWindow(value){let parsed={immediate:0,"5s":5,"30s":30,"1m":60}[value.toLowerCase()];if(parsed===void 0)throw new WebhookCommandError("WEBHOOK_GROUPING_INVALID",`Invalid grouping window '${value}'. Use immediate, 5s, 30s, or 1m.`);return parsed}__name(parseEntryBatchWindow,"parseEntryBatchWindow");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path53=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile6(path53,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path53}'.`)}}return parseJson(input,flag2)}__name(parseJsonInput,"parseJsonInput");async function readStdin2(){let input="";process.stdin.setEncoding("utf8");for await(let chunk of process.stdin)input+=chunk;return input}__name(readStdin2,"readStdin");function parseJsonObject3(value,flag2){let parsed=parseJson(value,flag2);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new WebhookCommandError("WEBHOOK_DATA_INVALID",`${flag2} must be a JSON object.`);return parsed}__name(parseJsonObject3,"parseJsonObject");function parseOnOff(value,flag2){if(value==="on")return!0;if(value==="off")return!1;throw new WebhookCommandError("WEBHOOK_TOGGLE_INVALID",`${flag2} must be 'on' or 'off'.`)}__name(parseOnOff,"parseOnOff");function renderJson(command,data2){ui.result({command,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","logs","validate","update","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["environments","status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
|
|
1468
1482
|
`)}__name(formatHelpWithGroupedCommands,"formatHelpWithGroupedCommands");function formatGroupedCommandSections(cmd,helper,groups,termWidth){let visibleCommands=helper.visibleCommands(cmd);if(visibleCommands.length===0)return[];let commandByName=new Map(visibleCommands.map(command=>[command.name(),command])),renderedNames=new Set,sections=[];for(let group of groups){let rows=group.commands.map(name=>commandByName.get(name)).filter(command=>command!==void 0).map(command=>(renderedNames.add(command.name()),indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper))));rows.length>0&&(sections.length>0&§ions.push(""),sections.push(` ${group.title}:`,...rows))}let ungroupedRows=visibleCommands.filter(command=>!renderedNames.has(command.name())).map(command=>indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper)));return ungroupedRows.length>0&&(sections.length>0&§ions.push(""),sections.push(" Other commands:",...ungroupedRows)),sections}__name(formatGroupedCommandSections,"formatGroupedCommandSections");function indentBlock(value){return value.split(`
|
|
1469
1483
|
`).map(line=>` ${line}`).join(`
|
|
1470
|
-
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_branch_option();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs51.readFileSync(path52.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs51.readFileSync(path52.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--branch <name>","Override the Fimo Branch this command targets (defaults to the current git branch, falling back to `main`)").option("--env <name>","Deprecated alias for --branch. Passing both with different values is an error.").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerMcpCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--branch <name>","Branch to clone (defaults to main)").option("--env <name>","Deprecated alias for --branch").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--branch <name>","Branch to link (defaults to the current git branch, else main)").option("--env <name>","Deprecated alias for --branch").option("--relink","Replace an existing link to a different project").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--branch <name>","Branch to check out when linking an existing project (defaults to main)").option("--env <name>","Deprecated alias for --branch").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory when creating").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Set up the migration target: crawl a live site into draft artifacts, or link/create the Fimo project for a source-backed migration").argument("[target]","Published source site URL to crawl, or a target project directory for a source-backed migration").argument("[dir]","Target Fimo project directory for a URL migration (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--project-id <projectId>","Link an owner-supplied existing project (source-backed migration; delegates to `fimo init`)").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action((target,dir,_options,command)=>migrateInitCommand(target,dir,command.optsWithGlobals()));migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the URL migration manifest, or of the canonical .fimo/migration ledger").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the URL-crawl draft manifest (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the URL-crawl draft toward the source site (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print the import plan as regular Fimo CLI commands; writes no data").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--no-wait","Don't wait for the deployed preview to serve a page. Validation, push, and sandbox sync are still waited for; the result reports readiness as skipped. Not a substitute for --no-restart.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);addPaginationOptions(program.command("logs").description("Show the current Branch sandbox's dependency-install and dev-server output (newest first)"),{defaultLimit:200,maxLimit:1e3,legacyCursor:"before"}).option("-C, --cwd <dir>","Run against this directory instead of cwd").addHelpText("after",`
|
|
1484
|
+
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_branch_option();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs51.readFileSync(path52.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs51.readFileSync(path52.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--branch <name>","Override the Fimo Branch this command targets (defaults to the current git branch, falling back to `main`)").option("--env <name>","Deprecated alias for --branch. Passing both with different values is an error.").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerMcpCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--branch <name>","Branch to clone (defaults to main)").option("--env <name>","Deprecated alias for --branch").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--branch <name>","Branch to link (defaults to the current git branch, else main)").option("--env <name>","Deprecated alias for --branch").option("--relink","Replace an existing link to a different project").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--branch <name>","Branch to check out when linking an existing project (defaults to main)").option("--env <name>","Deprecated alias for --branch").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory when creating").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--source-platform <platform>","Where the site comes from: webflow | framer | squarespace | wix | carrd | wordpress | nextjs | astro | react-router | other (defaults to the platform detected by the crawl)").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Set up the migration target: crawl a live site into draft artifacts, or link/create the Fimo project for a source-backed migration").argument("[target]","Published source site URL to crawl, or a target project directory for a source-backed migration").argument("[dir]","Target Fimo project directory for a URL migration (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--project-id <projectId>","Link an owner-supplied existing project (source-backed migration; delegates to `fimo init`)").option("--org <organizationId>","Target organization ID when creating a new project").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--source-platform <platform>","Where the site comes from: webflow | framer | squarespace | wix | carrd | wordpress | nextjs | astro | react-router | other (URL migrations default to the platform detected by the crawl)").option("--json","Output the resulting manifest as JSON").action((target,dir,_options,command)=>migrateInitCommand(target,dir,command.optsWithGlobals()));migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the URL migration manifest, or of the canonical .fimo/migration ledger").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the URL-crawl draft manifest (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the URL-crawl draft toward the source site (URL migrations only)").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print the import plan as regular Fimo CLI commands; writes no data").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--no-wait","Don't wait for the deployed preview to serve a page. Validation, push, and sandbox sync are still waited for; the result reports readiness as skipped. Not a substitute for --no-restart.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);addPaginationOptions(program.command("logs").description("Show the current Branch sandbox's dependency-install and dev-server output (newest first)"),{defaultLimit:200,maxLimit:1e3,legacyCursor:"before"}).option("-C, --cwd <dir>","Run against this directory instead of cwd").addHelpText("after",`
|
|
1471
1485
|
Logs come from the sandbox's own process buffers, so they end when the sandbox does.
|
|
1472
1486
|
There is no --follow; re-run the command instead.
|
|
1473
|
-
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("update").description("Update this checkout's Fimo packages to an exact release and apply the bundled migrations").argument("<version>","Exact target version, for example 1.0.0").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--dry-run","Show the update plan without writing anything").option("--apply","Apply without prompting (required in --json / non-interactive shells)").option("--allow-dirty","Skip the clean-working-tree check").option("--no-install","Skip dependency installation after applying").option("--no-validate","Skip `fimo validate` after applying").action(updateCommand3);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--branch <name>","Branch to clone (defaults to main)").option("--env <name>","Deprecated alias for --branch").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete Branches (a Branch = git branch + its own Neon DB + sandbox)").argument("[name]","Branch name (omit to list)").option("-v, --verbose","Include deleted Branches").option("--all","Also list Fimo's own agent Branches (task/*), normally hidden").option("-d, --delete","Delete the named Branch (drops sandbox + Neon branch + R2 prefix)").option("--from <branch>","Parent Branch to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to a Branch (or create + switch with -b)").argument("<name>","Branch name").option("-b, --create","Create the Branch if it does not exist").option("--from <branch>","Parent Branch (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch Branches)").argument("<name>","Branch name").action(checkoutCommand);program.command("pull").description("Sync the current Branch's data plane from its parent").option("--from <branch>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-Branch diff across all surfaces").argument("[from]","From Branch (defaults to the current Branch)").argument("[to]","To Branch (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another Branch into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source Branch").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);var publish=program.command("publish").description("Publish main using a stable Fimo publication ID").option("-C, --cwd <dir>","Project directory").option("--label <text>","Optional human-readable publication label").option("--notes <text>","Optional publication notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);addPaginationOptions(publish.command("list").description("Publication attempts for the current project, newest first"),{defaultLimit:20,maxLimit:100,legacyCursor:"before"}).option("-C, --cwd <dir>","Project directory").action(publishListCommand);publish.command("inspect").description("One publication attempt in full, including why it failed").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").action(publishInspectCommand);publish.command("logs").description("Read a publication's build log from its hosting provider").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Events to return (1-1000, default 200)").action(publishLogsCommand);program.command("status").description("Multi-surface Branch status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <branch>","Comparison target (defaults to the parent Branch or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");addPaginationOptions(entries.command("list").description("List entries of a content type"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");addPaginationOptions(assets2.command("list").description("List assets"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").action(assetsListCommand);assets2.command("read").description("Read canonical asset text or ask one targeted question").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--cursor <next-cursor>","Continue an exact read from a previous nextCursor").option("--query <question>","Ask one targeted model-backed question").action(assetsReadCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);assets2.command("bulk-upload").description("Upload files from a structured JSON manifest").requiredOption("--file <path>","JSON manifest path").option("-C, --cwd <dir>","Project directory").option("--concurrency <n>","Maximum parallel uploads","4").action(assetsBulkUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("usage").description("Check Current, Main, and Live structured-reference impact").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsUsageCommand);assets2.command("replace").description("Replace structured references in the Current Branch").argument("<id>","Source asset ID").requiredOption("--with <id>","Replacement asset ID").option("-C, --cwd <dir>","Project directory").action(assetsReplaceCommand);assets2.command("remove").alias("delete").description("Safely remove an asset from this environment").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--replace-with <id>","Replace references before removal (Current Branch; every Branch and Live with --permanent)").option("--without-checking","Skip reference guidance before environment removal").option("--permanent","Destroy the asset across the project").option("-y, --yes","Skip confirmation for permanent destruction").action(assetsRemoveCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1487
|
+
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("update").description("Update this checkout's Fimo packages to an exact release and apply the bundled migrations").argument("<version>","Exact target version, for example 1.0.0").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--dry-run","Show the update plan without writing anything").option("--apply","Apply without prompting (required in --json / non-interactive shells)").option("--allow-dirty","Skip the clean-working-tree check").option("--no-install","Skip dependency installation after applying").option("--no-validate","Skip `fimo validate` after applying").action(updateCommand3);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--branch <name>","Branch to clone (defaults to main)").option("--env <name>","Deprecated alias for --branch").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete Branches (a Branch = git branch + its own Neon DB + sandbox)").argument("[name]","Branch name (omit to list)").option("-v, --verbose","Include deleted Branches").option("--all","Also list Fimo's own agent Branches (task/*), normally hidden").option("-d, --delete","Delete the named Branch (drops sandbox + Neon branch + R2 prefix)").option("--from <branch>","Parent Branch to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to a Branch (or create + switch with -b)").argument("<name>","Branch name").option("-b, --create","Create the Branch if it does not exist").option("--from <branch>","Parent Branch (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch Branches)").argument("<name>","Branch name").action(checkoutCommand);program.command("pull").description("Sync the current Branch's data plane from its parent").option("--from <branch>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-Branch diff across all surfaces").argument("[from]","From Branch (defaults to the current Branch)").argument("[to]","To Branch (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another Branch into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source Branch").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);var publish=program.command("publish").description("Publish main using a stable Fimo publication ID").option("-C, --cwd <dir>","Project directory").option("--label <text>","Optional human-readable publication label").option("--notes <text>","Optional publication notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);addPaginationOptions(publish.command("list").description("Publication attempts for the current project, newest first"),{defaultLimit:20,maxLimit:100,legacyCursor:"before"}).option("-C, --cwd <dir>","Project directory").action(publishListCommand);publish.command("inspect").description("One publication attempt in full, including why it failed").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").action(publishInspectCommand);publish.command("logs").description("Read a publication's build log from its hosting provider").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Events to return (1-1000, default 200)").action(publishLogsCommand);program.command("status").description("Multi-surface Branch status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <branch>","Comparison target (defaults to the parent Branch or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");addPaginationOptions(entries.command("list").description("List entries of a content type"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");addPaginationOptions(assets2.command("list").description("List assets"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").action(assetsListCommand);assets2.command("read").description("Read canonical asset text or ask one targeted question").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--cursor <next-cursor>","Continue an exact read from a previous nextCursor").option("--query <question>","Ask one targeted model-backed question").action(assetsReadCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);assets2.command("bulk-upload").description("Upload files from a structured JSON manifest").requiredOption("--file <path>","JSON manifest path").option("-C, --cwd <dir>","Project directory").option("--concurrency <n>","Maximum parallel uploads","4").action(assetsBulkUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("usage").description("Check Current, Main, and Live structured-reference impact").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsUsageCommand);assets2.command("replace").description("Replace structured references in the Current Branch").argument("<id>","Source asset ID").requiredOption("--with <id>","Replacement asset ID").option("-C, --cwd <dir>","Project directory").action(assetsReplaceCommand);assets2.command("remove").alias("delete").description("Safely remove an asset from this environment").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--replace-with <id>","Replace references before removal (Current Branch content and source; every Branch and Live with --permanent)").option("--without-checking","Skip reference guidance before environment removal").option("--permanent","Destroy the asset across the project").option("-y, --yes","Skip confirmation for permanent destruction").action(assetsRemoveCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1474
1488
|
Supported agents:
|
|
1475
1489
|
Universal (always covered via AGENTS.md, no per-agent file needed):
|
|
1476
1490
|
Codex, OpenCode, Aider, and other AGENTS.md-native tools
|