fimo 2.2.0-staging.10 → 2.2.0-staging.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/assets/skills/fimo-cli/SKILL.md +1 -1
  2. package/assets/skills/fimo-cli/references/assets.md +38 -2
  3. package/assets/skills/fimo-migration/SKILL.md +44 -13
  4. package/assets/skills/fimo-migration/references/frameworks/nextjs.md +8 -0
  5. package/assets/skills/fimo-migration/references/qa.md +30 -4
  6. package/assets/skills/fimo-migration/references/questions-and-improvements.md +188 -0
  7. package/assets/skills/fimo-migration/references/workers/content-planner.md +8 -3
  8. package/assets/skills/fimo-migration/references/workers/validator.md +20 -6
  9. package/assets/skills/fimo-migration/references/workers.md +17 -6
  10. package/assets/skills/fimo-migration/references/workflow.md +33 -6
  11. package/assets/skills/fimo-studio/SKILL.md +3 -1
  12. package/assets/skills/fimo-studio/references/agents.md +25 -0
  13. package/dist/cli/bundle.json +1 -1
  14. package/dist/cli/index.js +12 -11
  15. package/dist/runtime/templates.d.ts +1 -0
  16. package/dist/runtime/templates.js +3 -0
  17. package/package.json +8 -7
  18. package/templates/astro/package.json +2 -2
  19. package/templates/nextjs/package.json +3 -3
  20. package/templates/react-router/package.json +4 -4
  21. package/templates/sveltekit/package.json +2 -2
  22. package/templates/vite/package.json +4 -4
  23. package/templates/welcome/manifest.json +404 -0
  24. package/templates/welcome/media/analytics-overview.avif +0 -0
  25. package/templates/welcome/media/autonomous-loop.avif +0 -0
  26. package/templates/welcome/media/editable-preview.avif +0 -0
  27. package/templates/welcome/media/media-library.avif +0 -0
  28. package/templates/welcome/media/slack-teams.avif +0 -0
  29. package/templates/welcome/template/.fimo/agents/welcome-guide/GOAL.md +7 -0
  30. package/templates/welcome/template/.fimo/agents/welcome-guide/config.yaml +8 -0
  31. package/templates/welcome/template/.fimo/config.json +53 -0
  32. package/templates/welcome/template/src/font.css +60 -0
  33. package/templates/welcome/template/src/pages/ArticleDetail.tsx +68 -0
  34. package/templates/welcome/template/src/pages/Index.tsx +32 -0
  35. package/templates/welcome/template/src/pages/SiteContent.tsx +413 -0
  36. package/templates/welcome/template/src/pages/fallback-content.ts +133 -0
  37. package/templates/welcome/template/src/routes.ts +9 -0
  38. package/templates/welcome/template/src/schemas/Article.json +12 -0
  39. package/templates/welcome/template/src/schemas/Article.ts +59 -0
  40. package/templates/welcome/template/src/schemas/Article.types.ts +73 -0
  41. package/templates/welcome/template/src/schemas/HomePage.json +39 -0
  42. package/templates/welcome/template/src/schemas/HomePage.types.ts +114 -0
package/dist/cli/index.js CHANGED
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
39
39
  `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process8.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process8.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
40
40
  `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=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_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,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)}),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 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(`
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
 
@@ -57,13 +57,14 @@ ${block.code}
57
57
 
58
58
  `)}function flattenReportDocument(document){let sections=[`# ${document.title}`,...document.brief.map(reportBlockMarkdown)];return document.details.length>0&&sections.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(),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)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z24.array(AgentListItemDTOSchema))}});import{z as z25}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=z25.object({args:z25.unknown().optional(),requestId:z25.string().min(1).max(128).optional()}),DispatchSkippedSchema=z25.object({skipped:z25.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z25.object({sessionId:z25.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z25.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z26}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=z26.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.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=z26.enum(CONFLICT_KINDS),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:ConflictKindSchema.optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:BranchSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}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=z27.enum(["planned","running","finished","cancelled","errored"]),AgentRunStatusSchema=z27.enum(["in-progress","done","merge-required","needs-attention","needs-input","failed"]),AgentSessionsListQuerySchema=z27.object({env:z27.string().optional(),project_agents_only:z27.coerce.boolean().optional(),agent_name:z27.string().optional(),status:AgentSessionStatusSchema.optional(),run_status:AgentRunStatusSchema.optional(),since:z27.coerce.date().optional(),page:z27.coerce.number().int().positive().default(1),limit:z27.coerce.number().int().positive().max(200).default(25),cursor:z27.coerce.date().optional()}),SessionMetricsSchema=z27.object({cpuMs:z27.number().nonnegative().default(0),netBytes:z27.number().nonnegative().default(0),walltimeMs:z27.number().nonnegative().default(0),llmTokensIn:z27.number().nonnegative().optional(),llmTokensOut:z27.number().nonnegative().optional(),stepCount:z27.number().int().nonnegative().optional(),toolCallCounts:z27.record(z27.string().min(1).max(120),z27.number().int().nonnegative()).optional(),toolCallOutcomes:z27.array(z27.object({toolName:z27.string().min(1).max(120),success:z27.boolean(),code:z27.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional()})).max(512).optional(),finishAction:z27.enum(["merge","retain","discard"]).optional()}),AgentSessionReviewPublicationSchema=z27.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z27.object({capturedAt:z27.coerce.date(),fingerprint:z27.string().min(1).max(256),counts:z27.object({code:z27.number().int().nonnegative(),content:z27.number().int().nonnegative(),schemas:z27.number().int().nonnegative(),labels:z27.number().int().nonnegative(),assets:z27.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z27.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z27.object({diff:DiffReportSchema,code:z27.array(CodeFileDiffSchema.extend({raw:z27.string().max(24576)})).max(200),schemas:z27.array(SchemaTypeDiffSchema).max(200),content:z27.array(z27.object({key:z27.string().min(1).max(512),collection:z27.string().min(1).max(256),slug:z27.string().max(512).optional(),verb:z27.enum(["added","modified","deleted"]),fields:z27.array(z27.object({name:z27.string().min(1).max(256),before:z27.unknown().optional(),after:z27.unknown().optional()})).max(20)})).max(200),labels:z27.array(z27.object({key:z27.string().min(1).max(512),locale:z27.string().min(1).max(64).optional(),before:z27.unknown().nullable(),after:z27.unknown().nullable()})).max(200),assets:z27.array(z27.object({key:z27.string().min(1).max(512),name:z27.string().min(1).max(512),verb:z27.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z27.object({id:z27.uuid(),projectId:z27.uuid(),env:BranchSchema,agentName:z27.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z27.unknown().optional(),capabilities:z27.array(z27.string()).optional(),dataSources:z27.array(z27.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z27.string().nullable(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),cancelledAt:z27.coerce.date().nullable(),costUsd:z27.number().nonnegative(),costCeilingUsd:z27.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z27.boolean(),lastCheckpointId:z27.uuid().nullable(),branchEnvId:z27.uuid().nullable(),parentSessionId:z27.uuid().nullable(),terminalReason:z27.string().nullable(),errorMessage:z27.string().nullable(),reportDocument:ReportDocumentSchema.nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z27.object({id:z27.uuid(),sessionId:z27.uuid(),checkpointIdx:z27.number().int().nonnegative(),payloadRef:z27.string(),payloadSizeBytes:z27.number().int().nonnegative(),checksum:z27.string().length(64),createdAt:z27.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createPaginatedResponseSchema(AgentSessionDTOSchema),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z27.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z27.object({session:AgentSessionDTOSchema,checkpoints:z27.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z27.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=z27.object({reason:z27.string().min(1).max(120).optional()})}});import{z as z28}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=z28.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z28.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z28.object({id:z28.uuid(),envId:z28.uuid(),sessionId:z28.uuid().nullable(),skillName:z28.string().min(1),classification:AgentBranchClassificationSchema,rationale:z28.string().nullable(),summary:z28.string().nullable(),surfaceDeltas:z28.record(z28.string(),z28.unknown()),createdAt:z28.coerce.date(),decidedAt:z28.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z28.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z28.object({path:z28.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z28.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z28.object({code:z28.literal("merge_conflict"),message:z28.string(),conflicts:z28.record(z28.string(),z28.number().int().nonnegative())})}});import{z as z29}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=z29.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z29.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=z29.object({description:z29.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z29.literal(QUESTION_FORM_CONTRACT_VERSION)}),AgentQuestionSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),threadId:z29.uuid(),invocationId:z29.uuid(),agentKey:z29.string().min(1).max(120),anchorEnv:z29.string().min(1).max(64),retainedEnv:z29.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z29.string().min(1).nullable(),continuationInvocationId:z29.uuid().nullable(),askedAt:z29.coerce.date(),expiresAt:z29.coerce.date(),closedAt:z29.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z29.object({questionId:z29.uuid(),invocationId:z29.uuid(),askedAt:z29.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z29.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z29.object({question:AgentQuestionSchema,continuationInvocationId:z29.uuid(),deduped:z29.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z30}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=z30.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z30.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z30.enum(["secret_text"]),IntegrationCredentialUsageSchema=z30.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z30.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z30.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z30.object({mode:IntegrationAuthModeSchema,label:z30.string().min(1),description:z30.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z30.object({id:z30.string().min(1),label:z30.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z30.boolean()}),IntegrationToolDefinitionDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),description:z30.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z30.object({title:z30.string().min(1),description:z30.string().min(1),command:z30.string().min(1).optional()}),IntegrationInfoDTOSchema=z30.object({key:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),type:z30.enum(["native","mcp"]).optional(),url:z30.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z30.array(IntegrationAuthModeDTOSchema),credentials:z30.array(IntegrationCredentialDefinitionDTOSchema),tools:z30.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z30.enum(["available","unavailable"]).optional(),recipes:z30.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),name:z30.string().min(1),summary:z30.string().min(1),installed:z30.boolean(),enabled:z30.boolean(),setupState:z30.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z30.string().nullable(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),connectionStatus:z30.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),installedAt:z30.coerce.date().nullable(),updatedAt:z30.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),enabled:z30.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z30.string(),connectionId:z30.uuid().nullable().optional(),connectionAlias:z30.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z30.array(z30.string()),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z30.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z30.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z30.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z30.object({value:z30.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z30.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z30.object({id:z30.uuid(),organizationId:z30.string().min(1),integrationKey:z30.string().min(1),alias:z30.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z30.string().min(1),externalAccountName:z30.string().nullable(),externalBotUserId:z30.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z30.array(z30.string()),connectedAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),McpHeaderNameSchema=z30.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z30.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z30.record(McpHeaderNameSchema,z30.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z30.object({alias:z30.string().min(1).max(120).optional(),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.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=z30.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),alias:z30.string().min(1).max(120),token:z30.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z30.boolean().optional()}),z30.object({mode:z30.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z30.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=z30.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z30.union([z30.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z30.object({type:z30.literal("mcp"),name:z30.string().trim().min(1).max(120),url:z30.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z30.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z30.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=z30.object({integrationKey:z30.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z30.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z30.literal("oauth"),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),ReusableMcpServerAuthKindSchema=z30.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z30.object({id:z30.uuid(),name:z30.string().min(1),host:z30.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z30.string().min(1),availability:z30.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z30.object({query:z30.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z30.object({serverId:z30.uuid()}),StartProjectIntegrationConnectResponseSchema=z30.object({integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z30.discriminatedUnion("mode",[z30.object({mode:z30.literal("personal"),integrationKey:z30.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z30.object({mode:z30.literal("oauth"),integrationKey:z30.string().min(1),connectUrl:z30.string().url(),expiresAt:z30.coerce.date()})]),BindProjectChannelRequestSchema=z30.object({ref:z30.string().min(1),connectionAlias:z30.string().min(1).optional(),agentName:z30.string().min(1).max(160).nullable().optional(),force:z30.boolean().optional()}),ListProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1)}),SearchProjectChannelsQuerySchema=z30.object({integrationKey:z30.string().min(1),connectionAlias:z30.string().min(1),query:z30.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z30.object({id:z30.uuid(),projectId:z30.uuid(),integrationKey:z30.string().min(1),connectionId:z30.uuid(),externalWorkspaceId:z30.string().min(1),externalChannelId:z30.string().min(1),externalChannelName:z30.string().nullable(),agentName:z30.string().nullable(),enabled:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z30.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z30.object({id:z30.string().min(1),name:z30.string().min(1),visibility:z30.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z30.string().min(1).nullable(),canMove:z30.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z30.object({markdown:z30.boolean().optional(),summary:z30.boolean().optional(),links:z30.boolean().optional(),branding:z30.boolean().optional(),images:z30.boolean().optional(),html:z30.union([z30.literal("cleaned"),z30.literal("raw"),z30.boolean()]).optional(),json:z30.union([z30.boolean(),z30.object({prompt:z30.string().min(1).max(1e4),schema:z30.record(z30.string(),z30.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z30.object({url:z30.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z30.object({query:z30.string().min(1),maxResults:z30.number().int().positive().max(20).optional(),sources:z30.array(z30.enum(["web","news","images"])).min(1).max(3).optional(),categories:z30.array(z30.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z30.enum(["hour","day","week","month","year"]).optional(),location:z30.string().min(1).max(160).optional(),country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(100).optional(),types:z30.array(z30.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),sources:z30.array(z30.string().min(1).max(512)).min(1).max(20).optional(),passages:z30.number().int().min(1).max(5).optional(),skills:z30.literal("only").optional(),language:z30.string().min(1).optional(),topic:z30.string().min(1).optional(),license:z30.string().min(1).optional(),minStars:z30.number().int().min(0).optional(),maxStars:z30.number().int().min(0).optional(),archived:z30.boolean().optional(),fork:z30.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z30.object({query:z30.string().min(1).max(500),maxResults:z30.number().int().min(1).max(500).optional(),authors:z30.array(z30.string().min(1)).min(1).optional(),categories:z30.array(z30.string().min(1)).min(1).optional(),from:z30.iso.date().optional(),to:z30.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),query:z30.string().min(1).max(500).optional(),maxPassages:z30.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z30.object({paperId:z30.string().min(1).max(512),intent:z30.string().min(1).max(500),mode:z30.enum(["similar","citers","references"]).optional(),maxResults:z30.number().int().min(1).max(500).optional(),rerank:z30.boolean().optional(),anchors:z30.array(z30.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z30.object({url:z30.string().url(),search:z30.string().min(1).optional(),limit:z30.number().int().positive().max(200).optional(),includeSubdomains:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z30.object({url:z30.string().url(),limit:z30.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z30.object({text:z30.string().min(1).max(200).optional(),cron:z30.string().min(1).max(120).optional(),timezone:z30.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z30.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z30.boolean().optional(),timeoutMs:z30.number().int().positive().max(12e4).optional(),waitForMs:z30.number().int().min(0).max(3e4).optional(),maxAgeMs:z30.number().int().min(0).optional(),minAgeMs:z30.number().int().min(0).optional(),storeInCache:z30.boolean().optional(),proxy:z30.enum(["basic","enhanced","auto"]).optional(),mobile:z30.boolean().optional(),location:z30.object({country:z30.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z30.array(z30.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z30.union([z30.object({type:z30.enum(["scrape","crawl"]).default("scrape"),urls:z30.array(z30.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z30.object({type:z30.literal("search"),queries:z30.array(z30.string().min(1).max(256)).min(1).max(12),searchWindow:z30.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z30.number().int().min(1).max(50).optional(),includeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z30.array(z30.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z30.object({name:z30.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),notification:z30.object({email:z30.object({enabled:z30.boolean().default(!0),recipients:z30.array(z30.string().email()).min(1).max(20),includeDiffs:z30.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=z30.object({monitorId:z30.string().uuid(),name:z30.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z30.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z30.string().min(1).max(2e3).optional(),judgeEnabled:z30.boolean().optional(),retentionDays:z30.number().int().min(1).max(365).optional(),status:z30.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z30.object({monitorId:z30.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z30.string().uuid()}),RunProjectIntegrationToolRequestSchema=z30.object({tool:z30.string().min(1),input:z30.record(z30.string(),z30.unknown()),connectionAlias:z30.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z30.object({provider:z30.string().min(1),providerCredits:z30.number().nonnegative().optional(),providerCostUsd:z30.number().nonnegative().optional(),requests:z30.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z30.object({credits:z30.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),json:z30.unknown().optional(),branding:z30.record(z30.string(),z30.unknown()).optional(),warning:z30.string().optional()}),FirecrawlSearchToolOutputSchema=z30.object({query:z30.string(),provider:z30.literal("firecrawl"),warning:z30.string().optional(),results:z30.array(z30.object({title:z30.string(),url:z30.string(),snippet:z30.string().optional(),content:z30.string().optional(),score:z30.number().optional(),publishedAt:z30.string().optional()}))}),FirecrawlResearchPaperSchema=z30.object({paperId:z30.string(),primaryId:z30.string().optional(),ids:z30.record(z30.string(),z30.array(z30.string())).optional(),title:z30.string().optional(),abstract:z30.string().optional(),score:z30.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z30.object({text:z30.string(),score:z30.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(z30.object({id:z30.string(),type:z30.string().min(1).optional(),url:z30.string(),title:z30.string().optional(),passages:z30.array(z30.object({text:z30.string()}).passthrough())}).passthrough()),coverage:z30.record(z30.string(),z30.string()).optional(),reranked:z30.boolean().optional(),repos:z30.array(z30.record(z30.string(),z30.unknown())).optional(),sources:z30.array(z30.record(z30.string(),z30.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),paper:z30.record(z30.string(),z30.unknown()),paperId:z30.string().optional(),query:z30.string().optional(),passages:z30.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),results:z30.array(FirecrawlResearchPaperSchema),poolSize:z30.number().int().nonnegative(),truncated:z30.boolean(),note:z30.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),count:z30.number(),links:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),description:z30.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z30.object({url:z30.string(),provider:z30.literal("firecrawl"),total:z30.number(),pages:z30.array(z30.object({url:z30.string(),title:z30.string().optional(),statusCode:z30.number().optional(),markdown:z30.string().optional(),summary:z30.string().optional(),links:z30.array(z30.string()).optional(),images:z30.array(z30.string()).optional(),html:z30.string().optional(),warning:z30.string().optional()})),warning:z30.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z30.object({cron:z30.string().optional(),text:z30.string().optional(),timezone:z30.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z30.object({id:z30.string().optional(),type:z30.enum(["scrape","crawl","search"]).optional(),urls:z30.array(z30.string()).optional(),queries:z30.array(z30.string()).optional(),searchWindow:z30.string().optional(),maxResults:z30.number().optional(),includeDomains:z30.array(z30.string()).optional(),excludeDomains:z30.array(z30.string()).optional(),scrapeOptions:z30.record(z30.string(),z30.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z30.object({id:z30.string(),name:z30.string(),status:z30.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z30.string().nullable().optional(),lastRunAt:z30.string().nullable().optional(),currentCheckId:z30.string().nullable().optional(),targets:z30.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z30.string().nullable().optional(),judgeEnabled:z30.boolean().optional(),estimatedCreditsPerMonth:z30.number().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z30.object({id:z30.string(),monitorId:z30.string(),scheduledFor:z30.string().nullable().optional(),startedAt:z30.string().nullable().optional(),finishedAt:z30.string().nullable().optional(),estimatedCredits:z30.number().optional(),reservedCredits:z30.number().optional(),actualCredits:z30.number().optional(),billingStatus:z30.string().nullable().optional(),summary:z30.object({totalPages:z30.number().optional(),same:z30.number().optional(),changed:z30.number().optional(),new:z30.number().optional(),removed:z30.number().optional(),error:z30.number().optional()}).passthrough().optional(),error:z30.string().nullable().optional(),createdAt:z30.string().optional(),updatedAt:z30.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitors:z30.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),deleted:z30.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),checks:z30.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z30.object({provider:z30.literal("firecrawl"),monitorId:z30.string(),check:FirecrawlMonitorCheckOutputSchema,next:z30.string().optional()}),FirecrawlToolKeySchema=z30.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=z30.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z30.object({projectId:z30.uuid(),integrationKey:z30.string().min(1),tool:z30.string().min(1),connectionAlias:z30.string().min(1).nullable().optional(),output:z30.record(z30.string(),z30.unknown()),executedAt:z30.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z30.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z30.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z30.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z30.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z30.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z30.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z30.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z30.array(ProjectChannelCandidateDTOSchema))}});import{z as z31}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=z31.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z31.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z31.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z31.object({userId:z31.string().min(1),name:z31.string(),email:z31.string().min(1),subscribed:z31.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z31.object({maxSubscribers:z31.number().int().positive(),subscriberCount:z31.number().int().nonnegative(),effectiveRecipientCount:z31.number().int().nonnegative(),currentUserSubscribed:z31.boolean(),candidates:z31.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z31.object({userIds:z31.array(z31.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z31.object({topic:UserManagedNotificationTopicSchema,enabled:z31.boolean(),source:z31.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z31.object({topics:z31.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z31.object({enabled:z31.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z31.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z31.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z31.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z31.string().nullable(),maskedEmail:z31.string().min(1),applied:z31.boolean(),expiresAt:z31.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z31.object({scheduleId:z31.string().min(1),scheduleName:z31.string(),projectId:z31.string().min(1),projectName:z31.string(),env:z31.string().min(1)}),FollowedSchedulesSchema=z31.object({schedules:z31.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z32}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=z32.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=z32.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z32.uuid(),env:z32.string().min(1),name:z32.string().min(1),cron:z32.string().min(1),command:z32.string().min(1),secretKeys:z32.array(z32.string().min(1)),enabled:z32.boolean(),lastRunAt:z32.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z32.string().nullable(),overPolicyReasons:z32.array(z32.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120),cron:z32.string().min(1).max(120),command:z32.string().min(1).max(500),secretKeys:z32.array(ProjectSecretKeySchema).default([]),enabled:z32.boolean().optional()}),UpdateProjectScheduleRequestSchema=z32.object({name:z32.string().min(1).max(120).optional(),cron:z32.string().min(1).max(120).optional(),command:z32.string().min(1).max(500).optional(),secretKeys:z32.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z32.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z32.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z32.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z32.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z32.object({maxRuns:z32.number().int().positive(),retentionDays:z32.number().int().positive().nullable(),outputRetentionDays:z32.number().int().positive(),maxOutputBytes:z32.number().int().positive()}),SchedulePolicyStateSchema=z32.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z32.object({code:z32.enum(["Free","Premium","Pro"]),source:z32.enum(["cached_subscription","free_fallback"]),activeSchedules:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),concurrency:z32.object({used:z32.number().int().nonnegative(),limit:z32.number().int().positive()}),compute:z32.object({settledMs:z32.number().int().nonnegative(),reservedMs:z32.number().int().nonnegative(),includedMs:z32.number().int().positive(),remainingMs:z32.number().int().nonnegative(),resetsAt:z32.coerce.date()}),upgrade:z32.object({code:z32.literal("Pro"),activeSchedulesLimit:z32.number().int().positive(),minCadenceMinutes:z32.number().int().positive(),maxRunMs:z32.number().int().positive(),maxConcurrentRuns:z32.number().int().positive(),computeIncludedMs:z32.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z32.array(z32.string())}),ProjectScheduleUsageSchema=z32.object({runCount:z32.number().int().nonnegative(),runsWithOutput:z32.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z32.object({id:z32.uuid(),scheduleId:z32.uuid(),projectId:z32.uuid(),env:z32.string().min(1),scheduleName:z32.string().min(1),command:z32.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z32.object({id:z32.string().min(1),name:z32.string().min(1)}).nullable(),queuedAt:z32.coerce.date(),startedAt:z32.coerce.date().nullable(),finishedAt:z32.coerce.date().nullable(),exitCode:z32.number().int().nullable(),errorCode:z32.string().nullable(),error:z32.string().nullable(),outputBytes:z32.number().int().nonnegative(),outputTruncated:z32.boolean(),outputExpiresAt:z32.coerce.date().nullable(),metadataExpiresAt:z32.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z32.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z32.coerce.date().nullable(),items:z32.array(z32.object({key:z32.string().min(1),updatedAt:z32.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z32.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z32.object({trigger:z32.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z32.object({limit:z32.coerce.number().int().min(1).max(100).default(25),cursor:z32.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z32.object({items:z32.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z32.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z32.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z32.object({items:z32.array(ProjectScheduleRunDTOSchema),nextCursor:z32.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z33}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=z33.enum(WORK_NOTIFICATION_TOPICS),NOTIFICATION_CHANNELS=["in_app","email"],NotificationChannelSchema=z33.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z33.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("user"),userId:z33.string().min(1)}).strict(),z33.object({kind:z33.literal("agent"),agentKey:z33.string().min(1).max(120),agentId:z33.uuid().optional()}).strict(),z33.object({kind:z33.literal("system")}).strict()]),NotificationSummarySchema=z33.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z33.string().trim().min(1).max(120).optional(),brief:ReportBriefSchema.optional()},NotificationRunOutcomeSchema=z33.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z33.enum(["review","agent_requested","recovery"]),NotificationPayloadSchema=z33.discriminatedUnion("topic",[z33.object({topic:z33.literal("agent_question"),questionId:z33.uuid(),title:z33.string().trim().min(1).max(80),description:z33.string().trim().min(1).max(240)}).strict(),z33.object({topic:z33.literal("agent_run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().optional(),proposalId:z33.uuid().optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z33.object({topic:z33.literal("agent_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict()]),NotificationEnvelopeSchema=z33.object({id:z33.uuid(),projectId:z33.uuid(),sourceKey:z33.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z33.literal(1),payload:NotificationPayloadSchema,createdAt:z33.coerce.date()}),NotificationRecipientStateSchema=z33.object({id:z33.uuid(),notificationId:z33.uuid(),projectId:z33.uuid(),userId:z33.string().min(1),readAt:z33.coerce.date().nullable(),archivedAt:z33.coerce.date().nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationDeliveryStateSchema=z33.enum(["pending","sent","suppressed","failed"]),NotificationDeliverySchema=z33.object({id:z33.uuid(),notificationRecipientId:z33.uuid(),projectId:z33.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z33.number().int().nonnegative(),nextAttemptAt:z33.coerce.date().nullable(),lastAttemptAt:z33.coerce.date().nullable(),sentAt:z33.coerce.date().nullable(),failureCode:z33.string().max(80).nullable(),createdAt:z33.coerce.date(),updatedAt:z33.coerce.date()}),NotificationPreferenceSchema=z33.object({topic:WorkNotificationTopicSchema,channel:z33.literal("email"),enabled:z33.boolean(),source:z33.enum(["default","explicit"])}),WorkNotificationPreferencesSchema=z33.object({topics:z33.array(NotificationPreferenceSchema)}),WorkNotificationPreferencesResponseSchema=createResponseSchema(WorkNotificationPreferencesSchema),NotificationSubjectSchema=z33.discriminatedUnion("kind",[z33.object({kind:z33.literal("question"),questionId:z33.uuid()}).strict(),z33.object({kind:z33.literal("run_outcome"),threadId:z33.uuid(),invocationId:z33.uuid(),outcome:NotificationRunOutcomeSchema}).strict(),z33.object({kind:z33.literal("retained_review"),threadId:z33.uuid(),invocationId:z33.uuid().nullable(),proposalId:z33.uuid().nullable(),reason:NotificationRetainedReasonSchema}).strict(),z33.object({kind:z33.literal("merge_conflict"),mergeId:z33.uuid(),threadId:z33.uuid().nullable()}).strict()]),NotificationViewSchema=z33.object({notification:NotificationEnvelopeSchema,recipient:NotificationRecipientStateSchema,subject:NotificationSubjectSchema}),NotificationViewResponseSchema=createResponseSchema(NotificationViewSchema),NotificationListSchema=z33.object({items:z33.array(NotificationViewSchema),nextCursor:z33.string().nullable(),unreadCount:z33.number().int().nonnegative()}),NotificationListResponseSchema=createResponseSchema(NotificationListSchema),ListNotificationsQuerySchema=z33.object({topic:WorkNotificationTopicSchema.optional(),actorKind:NotificationActorKindSchema.optional(),actorId:z33.string().min(1).max(120).optional(),sourceKey:z33.string().min(1).max(255).optional(),unread:z33.stringbool().optional(),archived:z33.stringbool().optional(),limit:z33.coerce.number().int().min(1).max(100).optional(),cursor:z33.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=z33.object({recipient:NotificationRecipientStateSchema,unreadCount:z33.number().int().nonnegative()}),NotificationStateResponseSchema=createResponseSchema(NotificationStateSchema),UpdateNotificationStateRequestSchema=z33.object({read:z33.boolean().optional(),archived:z33.boolean().optional()}).refine(body=>body.read!==void 0||body.archived!==void 0,"Provide at least one of read or archived.")}});import{z as z34}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z34.object({surface:SurfaceNameSchema,key:z34.string(),label:z34.string()}),InlineSchema=z34.object({text:z34.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z34.discriminatedUnion("type",[z34.object({type:z34.literal("paragraph"),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("preview"),ref:DiffRefSchema,caption:z34.string().optional()}),z34.object({type:z34.literal("code"),code:z34.string(),lang:z34.string().optional(),caption:z34.string().optional()}),z34.object({type:z34.literal("risk"),level:z34.enum(["warning","error"]),content:z34.array(InlineSchema).max(24)}),z34.object({type:z34.literal("list"),items:z34.array(z34.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z34.object({headline:z34.string(),blocks:z34.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z34.object({summary:EnvDiffSummarySchema,fingerprint:z34.string(),generatedAt:z34.coerce.date(),cached:z34.boolean().optional(),credits:z34.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z35}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z35.object({date:z35.string(),visitors:z35.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z35.object({key:z35.string(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z35.object({path:z35.string(),pageName:z35.string().nullable().optional(),visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z35.object({preset:z35.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z35.string(),requestedTo:z35.string(),effectiveFrom:z35.string(),effectiveTo:z35.string(),isRetentionLimited:z35.boolean(),groupBy:z35.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z35.object({date:z35.string(),content:z35.string(),updatedAt:z35.string(),updatedByUserId:z35.string()}),ProjectPageviewAnalyticsDTOSchema=z35.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z35.number().int().nonnegative(),pageviews:z35.number().int().nonnegative(),bounceRate:z35.number().min(0).max(100),viewsPerVisit:z35.number().nonnegative(),averageVisitDurationSeconds:z35.number().nonnegative(),visitorsSeries:z35.array(ProjectDailyVisitorsDTOSchema),topPages:z35.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z35.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z35.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z36}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z36.object({id:z36.string(),email:z36.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z36.coerce.date(),createdAt:z36.coerce.date(),inviterUserId:z36.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z36.object({id:z36.string(),token:z36.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z36.object({success:z36.boolean(),projectId:z36.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z37}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z37.object({id:z37.string(),name:z37.string(),image:z37.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z37.object({count:z37.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z37.object({counts:z37.object({signed_up:z37.int(),activated:z37.int()}),credits:z37.object({total:z37.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z37.email(),emailVerified:z37.boolean(),createdAt:z37.coerce.date(),updatedAt:z37.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z38}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z38.object({id:z38.string(),principalType:ProjectPrincipalTypeSchema,principalId:z38.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z38.coerce.date(),expiresAt:z38.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z38.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z38.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z38.record(z38.string(),z38.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z38.object({access:z38.array(ProjectAccessItemDTOSchema),invites:z38.array(ProjectInviteDTOSchema),organization:z38.object({name:z38.string().nullable(),logo:z38.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z38.object({success:z38.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z38.object({success:z38.boolean(),projectId:z38.uuid()}))}});import{z as z39}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z39.object({publicationStatus:PublicationStatusSchema,appUrl:z39.string().nullable(),lastPublishedAt:z39.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z40}from"zod";var 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=z40.object({name:z40.string().min(1),version:z40.string().min(1)}),PreviewBridgeCapabilitySchema=z40.object({integrated:z40.boolean(),packages:z40.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z40.object({url:z40.url(),expiresAt:z40.iso.datetime(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z40.object({name:z40.string().min(1),locator:z40.string().min(1).optional(),source:z40.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z40.object({kind:z40.literal("dependency_build_scripts_blocked"),packageManager:z40.enum(["pnpm","yarn","bun"]),packages:z40.array(z40.string()),targets:z40.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z40.string(),approvalKey:z40.string(),command:z40.string().optional(),approval:z40.object({id:z40.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z40.object({code:z40.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z40.string(),repair:PreviewInstallRepairSchema}),PreviewInstallPolicyApprovalRequestSchema=z40.object({approvalId:z40.uuid()}),PreviewInstallPolicyApprovalEventSchema=z40.discriminatedUnion("type",[z40.object({type:z40.literal("progress"),step:z40.enum(["approval","install","restart","readiness"]),message:z40.string()}),z40.object({type:z40.literal("approved")}),z40.object({type:z40.literal("complete")}),z40.object({type:z40.literal("error"),code:z40.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z40.string()})])}});import{z as z41}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z41.string(),slug:z41.string().nullable(),logo:z41.string().nullable(),metadata:z41.record(z41.string(),z41.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z41.object({id:z41.string(),name:z41.string(),email:z41.email(),image:z41.string().nullable()}),OrganizationMemberDTOSchema=z41.object({id:z41.string(),userId:z41.string(),organizationId:z41.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z41.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z42}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AgentRuntimeUsageStateSchema,AgentRuntimeUsageDTOSchema,AgentRuntimeUsageDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z42.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z42.object({reason:CancellationReasonCodeSchema,details:z42.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z42.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z42.object({offerVersion:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),renewsOn:z42.string()}),PlanMigrationPreviewDTOSchema=z42.object({currency:z42.string().trim().min(1),unusedPremiumCreditAmount:z42.number().int().nonnegative(),amountDueNow:z42.number().int().nonnegative(),startsAt:z42.string(),renewsAt:z42.string(),nextRenewalAmount:z42.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z42.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z42.object({id:z42.string(),organizationId:z42.string(),legacySubscriptionId:z42.string(),offeredPlanCode:z42.string(),offeredPlanName:z42.string(),offeredPriceAmount:z42.number(),offeredCurrency:z42.string(),offerVersion:z42.string(),state:PlanMigrationStateSchema,checkoutToken:z42.string().nullable(),deadlineAt:z42.string(),transitions:z42.array(z42.object({event:z42.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z42.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z42.object({included:z42.number().optional(),unitPrice:z42.number().optional(),dailyCap:z42.number().nullable().optional()}),EntitlementsDTOSchema=z42.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z42.object({retentionDays:z42.number().int().positive(),canUseExtendedDateRanges:z42.boolean()}).optional(),history:z42.object({retentionDays:z42.number().int().positive()}).optional(),members:z42.object({canInvite:z42.boolean(),maxMembers:z42.number().int().positive().nullable()}).optional(),domains:z42.object({canUseCustomDomains:z42.boolean(),maxDomains:z42.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z42.object({id:z42.string(),external_id:z42.string(),customerId:z42.string(),planId:z42.string(),planCode:z42.union([TemplateCodeSchema,z42.literal("Unknown")]),currentPeriod:z42.object({start:z42.string(),end:z42.string().nullable()}),cancelAt:z42.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z42.string(),nextPaymentAt:z42.string().nullable(),baseAmount:z42.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z42.object({totalCap:z42.number(),dailyCap:z42.number(),usedTotal:z42.number()}),CreditBalanceDTOSchema=z42.object({total:z42.number(),base:z42.number(),dailyBase:z42.number(),purchases:z42.number(),awards:z42.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z42.object({total:z42.number(),nearLimit:z42.boolean(),canChat:z42.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z42.object({dailyFreeAvailable:z42.number(),monthlyAvailable:z42.number(),purchasedAvailable:z42.number(),awardedAvailable:z42.number()}),ProjectDailyCreditAllowanceDTOSchema=z42.object({periodCap:z42.number(),dailyGrant:z42.number(),usedThisPeriod:z42.number(),remainingThisPeriod:z42.number()}),ProjectCreditBalanceDTOSchema=z42.object({projectId:z42.uuid(),organizationId:z42.string(),balance:z42.object({totalAvailable:z42.number(),nearLimit:z42.boolean(),canUseAi:z42.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z42.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AgentRuntimeUsageStateSchema=z42.enum(["ok","near_limit","exhausted"]),AgentRuntimeUsageDTOSchema=z42.object({planCode:z42.enum(["Free","Premium","Pro"]),state:AgentRuntimeUsageStateSchema,usage:z42.object({source:z42.enum(["cached_subscription","free_fallback"]),settledMs:z42.number().int().nonnegative(),reservedMs:z42.number().int().nonnegative(),includedMs:z42.number().int().positive(),remainingMs:z42.number().int().nonnegative(),resetsAt:z42.coerce.date()})}),AgentRuntimeUsageDTO=createDTO(AgentRuntimeUsageDTOSchema),AutoRefillConfigDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().nonnegative(),refillAmountUsd:z42.number().nonnegative()}),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().nonnegative().nullable(),refillAmountUsd:z42.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z42.discriminatedUnion("enabled",[z42.object({enabled:z42.literal(!0),thresholdUsd:z42.number().min(.01).multipleOf(.01),refillAmountUsd:z42.number().min(.01).multipleOf(.01)}).strict(),z42.object({enabled:z42.literal(!1),thresholdUsd:z42.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z42.object({invoiceId:z42.string(),newBalance:z42.int(),creditCount:z42.int(),amountUsd:z42.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z42.object({url:z42.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z43}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z43.object({brand:z43.string(),last4:z43.string(),exp:z43.string(),isDefault:z43.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z44}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z44.string().superRefine((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=z44.object({type:z44.literal("renameField"),contentType:z44.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z44.object({enabled:z44.boolean()}).strict(),ContentFieldGroupSchema=z44.object({id:z44.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z44.string().min(1).max(255),default:z44.boolean().optional()}).strict(),ContentTypeDTOSchema=z44.object({id:z44.string(),name:z44.string(),label:z44.string(),isSingleton:z44.boolean(),i18n:ContentTypeI18nSchema,groups:z44.array(ContentFieldGroupSchema).default([]),fields:z44.record(z44.string(),FieldDefinitionSchema),createdAt:z44.string(),updatedAt:z44.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z44.object({contentTypes:z44.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z44.object({id:z44.string(),entryId:z44.string(),documentId:z44.string(),slug:z44.string(),locale:z44.string().optional(),createdAt:z44.string(),updatedAt:z44.string(),__fimo:z44.object({contentType:z44.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({limit:z44.number(),offset:z44.number(),total:z44.number(),hasMore:z44.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z44.object({contentType:z44.string(),count:z44.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z44.object({counts:z44.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z44.object({count:z44.number().int().nonnegative(),sourceLocale:z44.string(),targetLocale:z44.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z44.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z44.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z44.union([z44.string(),z44.number(),z44.boolean(),z44.null()]),entryWhereOperatorSchema=z44.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z44.array(entryWhereScalarSchema).optional(),$nin:z44.array(entryWhereScalarSchema).optional(),$contains:z44.string().optional(),$startsWith:z44.string().optional(),$null:z44.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z44.record(z44.string(),z44.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z44.object({data:z44.record(z44.string(),z44.unknown()),locale:z44.string().min(1).optional(),documentId:z44.uuid().optional()}),entryIdsSchema=z44.array(z44.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z44.object({sql:z44.string().min(1)}),BulkCreateEntriesRequestSchema=z44.object({entries:z44.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z44.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z44.object({updates:z44.array(z44.object({id:z44.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z44.union([z44.object({ids:entryIdsSchema,locale:z44.string().min(1).optional()}),z44.object({where:EntryWhereSchema,locale:z44.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z44.object({data:z44.array(z44.record(z44.string(),z44.unknown())),meta:z44.object({rowCount:z44.number().int().nonnegative(),truncated:z44.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({created:z44.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({updated:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z44.object({data:z44.array(EntryDTOSchema),meta:z44.object({deleted:z44.number().int().nonnegative(),missing:z44.array(z44.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z45}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z45.object({index:z45.number().int().nonnegative(),contentType:z45.string(),field:z45.string(),value:z45.string(),against:z45.enum(["stored","batch"]),ownerDocumentId:z45.uuid().optional(),ownerIndex:z45.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z45.object({code:z45.literal("unique_conflict"),message:z45.string(),conflicts:z45.array(UniqueConflictSchema),truncated:z45.boolean().optional()})}});import{z as z46}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z46.object({kind:z46.literal("unique_conflict"),contentType:z46.string(),field:z46.string(),value:z46.string(),documentCount:z46.number().int().positive(),documentIds:z46.array(z46.uuid()),documentIdsTruncated:z46.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z46.object({code:z46.literal("schema_transition_rejected"),message:z46.string(),issues:z46.array(SchemaTransitionIssueSchema),truncated:z46.boolean().optional()})}});import{z as z47}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z47.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z47.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z47.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z47.object({field:CmsFieldNameSchema,direction:z47.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z47.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z47.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z47.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z47.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z47.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z48}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema))}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z51.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z51.object({items:z51.array(ProjectMessagePublicDTOSchema),nextCursor:z51.string().nullable()}),ChatLiveTurnDTOSchema=z51.object({invocationId:z51.string(),step:z51.enum(["preparing","working","compacting","merging"]),startedAt:z51.string()}),ChatLiveTurnStateDTOSchema=z51.object({threadId:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z51.object({id:z51.string(),role:z51.enum(["user","assistant"]),parts:z51.array(z51.unknown()),metadata:z51.record(z51.string(),z51.unknown()).nullable(),versionId:z51.string().nullable().optional(),createdAt:z51.date().transform(value=>value.toISOString()),providerMessageId:z51.string().nullable().optional(),invocationId:z51.string().nullable().optional(),invocationStatus:z51.string().nullable().optional(),invocationTerminalReason:z51.string().nullable().optional()}),ChatAttentionDTOSchema=z51.object({type:z51.literal("merge_conflict"),merge:z51.object({mergeId:z51.string().uuid(),projectId:z51.string(),fromEnv:z51.string(),toEnv:z51.string()}),publishAfterMerge:z51.boolean()}),ChatThreadMessagesPageDTOSchema=z51.object({threadId:z51.string().nullable(),title:z51.string().nullable(),messages:z51.array(ChatThreadMessageDTOSchema),nextCursor:z51.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z51.object({kind:z51.literal("replay"),threadId:z51.string(),userMessageId:z51.string()}),ChatQueuedOutcomeDTOSchema=z51.object({kind:z51.literal("queued"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string()}),ChatBusyOutcomeDTOSchema=z51.object({kind:z51.literal("busy"),threadId:z51.string(),userMessageId:z51.string(),blockingRootId:z51.string().optional()}),ChatRefusedOutcomeDTOSchema=z51.object({kind:z51.literal("refused"),threadId:z51.string(),userMessageId:z51.string(),refusedInvocationId:z51.string(),terminalReason:z51.string()}),ChatNonStreamingOutcomeDTOSchema=z51.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z51.object({success:z51.boolean(),deletedCount:z51.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z51.object({code:z51.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z51.string()})}});import{z as z52}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z52.object({url:z52.string().url(),key:z52.string(),size:z52.number(),contentType:z52.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z53}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z53.object({canAccess:z53.boolean(),permissions:z53.record(z53.string(),z53.boolean()),role:z53.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z54}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z54.string().trim().default(""),sort:z54.enum(["recent","name","relevance"]).default("recent"),category:z54.string().optional()})}});import{z as z55}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z55.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z55.enum(["fimo","external"]),PaymentStatusSchema=z55.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z55.object({id:z55.string().uuid(),domain:z55.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z55.boolean(),price:z55.number().int().nullable(),renewalPrice:z55.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z55.string().nullable(),failureReason:z55.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z55.object({domain:z55.string(),available:z55.boolean(),premium:z55.boolean(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),purchaseType:z55.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z55.object({domain:z55.string(),price:z55.number().nullable(),renewalPrice:z55.number().nullable(),premium:z55.boolean(),allowedYears:z55.array(z55.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z55.object({firstName:z55.string().max(100),lastName:z55.string().max(100),companyName:z55.string().max(100).optional(),address1:z55.string().max(255),address2:z55.string().max(255).optional(),city:z55.string().max(100),state:z55.string().max(100),zip:z55.string().max(20),country:z55.string().max(2),phone:z55.string().max(30),email:z55.union([z55.string().email().max(255),z55.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z55.object({firstName:z55.string().min(1).max(100),lastName:z55.string().min(1).max(100),companyName:z55.string().max(100).optional(),address1:z55.string().min(1).max(255),address2:z55.string().max(255).optional(),city:z55.string().min(1).max(100),state:z55.string().min(1).max(100),zip:z55.string().min(1).max(20),country:z55.string().min(1).max(2),phone:z55.string().min(1).max(30),email:z55.string().email().max(255)}),SearchDomainsRequestSchema=z55.object({keyword:z55.string().min(1).max(100),tldFilter:z55.array(z55.string()).optional()}),CheckAvailabilityRequestSchema=z55.object({domains:z55.array(z55.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z55.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z55.object({domain:DomainNameSchema,years:z55.number().int().min(1).max(10).optional().default(3),autoRenew:z55.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z55.object({autoRenew:z55.boolean().optional()}),RenewDomainRequestSchema=z55.object({years:z55.number().int().min(1).max(10).optional().default(1),autoRenew:z55.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z55.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z55.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z55.object({verified:z55.boolean(),email:z55.string().nullable(),verifyBy:z55.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z56}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z56.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z56.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z56.object({txtName:z56.string().nullable().optional(),txtValue:z56.string().nullable().optional(),httpUrl:z56.string().nullable().optional(),httpBody:z56.string().nullable().optional(),cname:z56.string().nullable().optional(),cnameTarget:z56.string().nullable().optional()}),SSLValidationErrorSchema=z56.object({message:z56.string()}),OwnershipVerificationSchema=z56.object({type:z56.string(),name:z56.string(),value:z56.string()}),ProjectDomainSSLDTOSchema=z56.object({status:z56.string(),method:z56.string().nullable(),type:z56.string().nullable(),validationRecords:z56.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z56.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z56.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z56.enum(["subdomain","apex"]),RedirectConfigSchema=z56.object({type:z56.literal("apex_to_www"),linkedDomainId:z56.string()}).nullable().optional(),ProjectDomainDTOSchema=z56.object({id:z56.string(),hostname:z56.string(),status:z56.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z56.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z56.string(),scdCnameTarget:z56.string().optional(),apexTargets:z56.array(z56.string()),dnsAutoConfigured:z56.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z56.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z56.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z56.object({hostname:z56.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z56.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z56.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z56.object({available:z56.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z56.object({success:z56.boolean(),hostname:z56.string()}))}});import{z as z57}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z57.object({available:z57.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z57.object({slug:z57.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z57.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z57.object({subdomain:z57.string(),subdomainUpdatedAt:z57.coerce.date()})),SubdomainSuggestionsQuerySchema=z57.object({base:z57.string().max(100).optional(),max:z57.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z57.object({suggestions:z57.array(z57.string())}))}});import{z as z58}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z58.object({translated:z58.number().int().nonnegative(),total:z58.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z58.object({locale:z58.string(),isDefault:z58.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z58.object({defaultLocale:z58.string(),locales:z58.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z58.object({locale:z58.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z58.object({locale:z58.string().min(1).max(40)}),ProjectLocaleMutationSchema=z58.object({locale:z58.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z58.object({locale:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z59}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z59.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z59.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z59.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z59.number(),credits:z59.number().optional(),billingMode:z59.enum(["fimo-credits","provider-account"]).optional(),confidence:z59.enum(["exact","estimated","metered"]),basis:z59.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z60}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z60.object({options:z60.record(z60.string(),z60.unknown()),name:z60.string().optional(),parentId:z60.string().nullable().optional(),altText:z60.string().optional(),caption:z60.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z60.string().min(1).optional(),model:z60.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z60.object({jobId:z60.string(),status:z60.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z60.string().nullable().optional(),credits:z60.number().optional(),costUsd:z60.number().optional(),billingMode:z60.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z60.object({error:z60.string(),code:z60.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z60.array(GenerationTaskIdSchema).optional(),availableModels:z60.array(z60.string()).optional(),issues:z60.array(z60.unknown()).optional()})}});import{z as z61}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z61.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z61.object({name:z61.string(),key:z61.string(),description:z61.string(),type:FlagTypeSchema,required:z61.boolean(),defaultValue:z61.unknown().optional(),enumValues:z61.array(z61.string()).optional(),isArray:z61.boolean()}),AssetModelPriceSchema=z61.object({unitPrice:z61.number(),unit:z61.string(),confidence:z61.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z61.object({id:z61.string(),shortName:z61.string(),provider:z61.string(),source:z61.string(),modality:z61.enum(["image","video","audio"]),tags:z61.array(z61.string()),displayName:z61.string(),description:z61.string(),flags:z61.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z61.object({model:z61.string(),costUsd:z61.number(),credits:z61.number(),billingMode:z61.enum(["fimo-credits","provider-account"]),confidence:z61.enum(["exact","estimated","metered"]),basis:z61.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z62}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z62.object({tourId:z62.string(),version:z62.string(),status:z62.string(),completedAt:z62.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z62.array(UserTourDTOSchema))}});import{z as z63}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z63.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z63.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z63.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z63.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z63.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z63.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z63.enum(["user","agent","system"]),SupportReportTagSchema=z63.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z63.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z63.object({organization:z63.object({id:z63.string().trim().min(1).max(255),name:z63.string().trim().max(240).optional()}),project:z63.object({id:z63.uuid(),name:z63.string().trim().max(240).optional(),createdAt:z63.coerce.date().optional()}).optional(),environment:z63.string().trim().max(255).optional(),clientVersion:z63.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z63.string().trim().max(200).optional(),limit:z63.coerce.number().int().min(1).max(100).default(50),offset:z63.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z63.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z63.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z63.uuid().nullable().optional(),note:z63.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z63.object({message:z63.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z63.object({kind:SupportReportLinkKindSchema,label:z63.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z63.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z63.object({kind:SupportReportActorKindSchema,id:z63.string().nullable(),name:z63.string().nullable()}),SupportReportLinkDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportLinkKindSchema,label:z63.string(),url:SupportReportHttpUrlSchema,externalId:z63.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z63.object({id:z63.uuid(),kind:SupportReportEventKindSchema,body:z63.string().nullable(),metadata:z63.record(z63.string(),z63.unknown()),actor:SupportReportActorDTOSchema,createdAt:z63.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z63.object({id:z63.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z63.array(z63.string()),source:SupportReportSourceSchema,message:z63.string(),reporter:z63.object({id:z63.string().nullable(),name:z63.string().nullable(),email:z63.string().nullable()}),organization:z63.object({id:z63.string().nullable(),name:z63.string()}),project:z63.object({id:z63.uuid().nullable(),name:z63.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z63.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z63.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z63.string().nullable(),deliveredAt:z63.coerce.date().nullable()}).nullable(),duplicateOfReportId:z63.uuid().nullable(),resolvedAt:z63.coerce.date().nullable(),createdAt:z63.coerce.date(),updatedAt:z63.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z63.string().nullable(),clientVersion:z63.string().nullable(),links:z63.array(SupportReportLinkDTOSchema),events:z63.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z63.object({reports:z63.array(SupportReportSummaryDTOSchema),total:z63.number().int().nonnegative(),statusCounts:z63.object({new:z63.number().int().nonnegative(),in_progress:z63.number().int().nonnegative(),waiting:z63.number().int().nonnegative(),resolved:z63.number().int().nonnegative(),duplicate:z63.number().int().nonnegative(),irrelevant:z63.number().int().nonnegative(),ignored:z63.number().int().nonnegative()}),limit:z63.number().int().positive(),offset:z63.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z63.object({id:z63.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z63.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z64}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z64.iso.datetime({offset:!0}).pipe(z64.coerce.date()),OpsRecentChatInputSchema=z64.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z64.string().trim().min(1).max(255).optional(),limit:z64.coerce.number().int().min(1).max(200).default(100),cursor:z64.string().trim().min(1).max(2e3).optional(),slim:z64.boolean().default(!0),reason:z64.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z64.object({id:z64.string(),threadId:z64.string(),providerMessageId:z64.string().nullable(),invocationId:z64.string().nullable(),env:z64.string().nullable(),role:z64.string(),parts:z64.array(z64.record(z64.string(),z64.unknown())),metadata:z64.object({status:z64.string().optional(),traceUrl:z64.string().optional(),externalFileChanges:z64.array(z64.unknown()).optional()}),stats:z64.object({toolCount:z64.number().int().nonnegative(),failedToolCount:z64.number().int().nonnegative()}),createdAt:z64.iso.datetime({offset:!0}),project:z64.object({id:z64.string(),name:z64.string(),displayName:z64.string().nullable(),organizationId:z64.string().nullable()})}),OpsRecentChatResponseSchema=z64.object({target:z64.object({backendProfile:OpsBackendProfileSchema,projectEnv:z64.string().nullable()}),window:z64.object({from:z64.iso.datetime({offset:!0}),to:z64.iso.datetime({offset:!0})}),messages:z64.object({items:z64.array(OpsRecentChatMessageSchema),nextCursor:z64.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z65}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z65.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z65.object({backendProfile:OpsBackendProfileSchema,provider:z65.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z65.literal(!1),reason:z65.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z66}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z66.object({packageManager:z66.string().trim().min(1).max(200).nullable(),trackedLockfiles:z66.array(z66.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z66.string().trim().min(1)}),OpsProjectPackageManagerSchema=z66.object({target:z66.object({backendProfile:OpsBackendProfileSchema,projectId:z66.uuid(),projectEnv:z66.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z67}from"zod";function createAgentRunWebhookEventDataSchema(status){return z67.object({run:z67.object({id:z67.string(),agentName:z67.string(),trigger:z67.string(),status:z67.literal(status),startedAt:z67.string().nullable(),finishedAt:z67.string().nullable(),reason:z67.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z67.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z67.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z67.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z67.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z67.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z67.union([z67.literal(0),z67.literal(5),z67.literal(30),z67.literal(60)]),EntryChangedWebhookEventDataSchema=z67.object({reason:WebhookEntryChangeReasonSchema,operationId:z67.string().optional(),batch:z67.object({index:z67.number().int().positive(),total:z67.number().int().positive()}).optional(),changes:z67.array(z67.object({action:WebhookEntryChangeActionSchema,contentType:z67.string(),id:z67.string(),documentId:z67.string(),locale:z67.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z67.object({form:z67.object({id:z67.string(),label:z67.string()}),submission:z67.object({id:z67.string(),data:z67.record(z67.string(),z67.unknown()),submittedAt:z67.string()})}),PublishStartedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("publishing"),startedAt:z67.string()})}),PublishSucceededWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("published"),url:z67.string(),publishedAt:z67.string(),firstPublish:z67.boolean()})}),PublishFailedWebhookEventDataSchema=z67.object({publication:z67.object({status:z67.literal("failed"),reason:z67.string()})}),PublishUnpublishedWebhookEventDataSchema=z67.object({publication:z67.object({previousUrl:z67.string(),unpublishedAt:z67.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),classification:z67.string(),summary:z67.string(),reasons:z67.array(z67.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z67.object({review:z67.object({id:z67.string(),runId:z67.string(),agentName:z67.string(),resolution:z67.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z67.object({report:z67.object({weekStart:z67.string(),weekEnd:z67.string(),pageviews:z67.number(),visitors:z67.number(),previousPageviews:z67.number(),previousVisitors:z67.number()})}),MediaAssetWebhookEventDataSchema=z67.object({id:z67.string().nullable(),name:z67.string().nullable(),type:z67.string(),mimeType:z67.string().nullable(),fileSize:z67.number().nullable()}),MediaUploadedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["updated","moved","analysis"]),analysis:z67.object({category:z67.string(),status:z67.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.literal("generated"),generation:z67.object({model:z67.string(),mode:z67.string()})}),MediaProcessingFailedWebhookEventDataSchema=z67.object({asset:MediaAssetWebhookEventDataSchema,operation:z67.enum(["analysis","generation"]),failure:z67.object({code:z67.string()})}),DomainCreatedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z67.object({domain:z67.object({id:z67.string(),hostname:z67.string()})}),LabelChangedWebhookEventDataSchema=z67.object({changes:z67.array(z67.object({action:z67.enum(["created","updated","deleted"]),key:z67.string(),locale:z67.string(),value:z67.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),isDefault:z67.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),previousCode:z67.string()})}),LocaleDeletedWebhookEventDataSchema=z67.object({locale:z67.object({code:z67.string(),entriesDeleted:z67.number().int().nonnegative(),labelsDeleted:z67.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z67.object({environment:z67.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z67.object({environment:z67.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z67.object({merge:z67.object({id:z67.string(),from:BranchSchema,to:BranchSchema,applied:z67.array(z67.object({surface:SurfaceNameSchema,count:z67.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z67.object({environment:z67.object({name:BranchSchema}),version:z67.object({versionId:z67.uuid(),name:z67.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z67.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z67.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z67.discriminatedUnion("source",[z67.object({source:z67.literal("literal"),value:z67.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z67.object({source:z67.literal("secret"),key:z67.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z67.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z67.object({name:z67.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z67.object({name:z67.string(),source:z67.enum(["literal","secret"]),secretKey:z67.string().nullable(),secretPrefix:z67.string().nullable(),configured:z67.literal(!0)}),WebhookFilterSchema=z67.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z67.string().min(1).max(255).optional(),agentName:z67.string().min(1).max(120).optional(),mediaType:z67.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z67.string().min(1).max(255).optional(),locale:z67.string().min(1).max(120).optional()}),JsonValueSchema=z67.lazy(()=>z67.union([z67.string(),z67.number(),z67.boolean(),z67.null(),z67.array(JsonValueSchema),z67.record(z67.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z67.url(),enabled:z67.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z67.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z67.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z67.object({name:z67.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z67.url().optional(),enabled:z67.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z67.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z67.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z67.object({eventType:WebhookEventTypeSchema.optional(),data:z67.record(z67.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z67.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z67.uuid(),name:z67.string(),eventType:WebhookEventTypeSchema,enabled:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z67.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z67.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z67.coerce.date().nullable(),deliveryStats24h:z67.object({succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z67.uuid(),projectId:z67.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z67.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z67.number().int().positive(),test:z67.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z67.number().int().nonnegative(),responseStatus:z67.number().int().nullable(),lastErrorCode:z67.string().nullable(),lastErrorMessage:z67.string().nullable(),payloadAvailable:z67.boolean(),destination:z67.object({host:z67.string(),maskedUrl:z67.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z67.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z67.string().nullable(),qstashMessageId:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z67.object({items:z67.array(WebhookDeliveryDTOSchema),pagination:z67.object({page:z67.number().int().positive(),limit:z67.number().int().positive(),total:z67.number().int().nonnegative(),totalPages:z67.number().int().positive(),hasMore:z67.boolean()}),stats:z67.object({total:z67.number().int().nonnegative(),succeeded:z67.number().int().nonnegative(),failed:z67.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z67.object({id:z67.uuid(),deliveryId:z67.uuid(),attempt:z67.number().int().positive(),status:z67.enum(["delivering","succeeded","failed"]),responseStatus:z67.number().int().nullable(),durationMs:z67.number().int().nonnegative(),responseExcerpt:z67.string().nullable(),errorCode:z67.string().nullable(),errorMessage:z67.string().nullable(),createdAt:z67.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z67.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z67.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z68}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z68.object({key:z68.literal("fimo-2"),enabled:z68.boolean(),dismissed:z68.boolean().default(!1),interacted:z68.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z69}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z69.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z69.object({total:z69.number(),base:z69.number(),purchases:z69.number(),awards:z69.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z69.object({id:z69.string(),name:z69.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z69.object({type:z69.string(),brand:z69.string().nullable(),last4:z69.string().nullable(),expirationDate:z69.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z69.object({currency:z69.string(),nextPaymentAmount:z69.number().nullable(),nextPaymentAt:z69.string().nullable(),billingInterval:z69.string().nullable(),totalAmount:z69.number().nullable(),discountAmount:z69.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z69.object({id:z69.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z69.string().nullable(),currentPeriodEndsAt:z69.string().nullable(),renewsAt:z69.string().nullable(),cancelAt:z69.string().nullable(),renewAutomatically:z69.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z69.object({type:z69.enum(["low_balance","critical_balance","approaching_limit"]),message:z69.string(),estimatedPromptsRemaining:z69.number().nullable(),avgCostPerPrompt:z69.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z69.object({monthlyCredits:z69.number().nullable(),usedThisPeriod:z69.number(),remainingThisPeriod:z69.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z69.object({organizationId:z69.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z69.string().nullable(),tenureDays:z69.number().int().nonnegative(),capturedAt:z69.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z69.object({hasSubscription:z69.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z69.number().nullable(),alerts:z69.array(CreditAlertDTOSchema),portalUrl:z69.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z69.object({creditCount:z69.number().int().positive(),expiresAt:z69.string().datetime().nullable().optional(),message:z69.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("free"),amountCents:z69.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z69.literal("purchase"),amountCents:z69.number().int().positive()}),CreditTopupRequestDTOSchema=z69.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z69.object({success:z69.boolean(),transactionId:z69.string().nullable(),newBalance:z69.number(),creditCount:z69.number(),type:z69.enum(["free","purchase"]),invoiceId:z69.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z70}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z70.object({totalCredits:z70.number(),totalCostUsd:z70.number(),totalMessages:z70.number(),avgCostPerMessage:z70.number(),periodStart:z70.string().nullable(),periodEnd:z70.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z70.object({date:z70.string(),credits:z70.number(),costUsd:z70.number(),messages:z70.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z70.object({userId:z70.string(),userName:z70.string().nullable(),userEmail:z70.string().email().nullable(),credits:z70.number(),costUsd:z70.number(),messages:z70.number(),percentage:z70.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z70.object({projectId:z70.string(),projectName:z70.string(),projectDisplayName:z70.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z70.array(UsageByUserForProjectDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z70.object({summary:UsageSummaryDTOSchema,byProject:z70.array(UsageByProjectDTOSchema),byUser:z70.array(UsageByUserDTOSchema),timeline:z70.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z71}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z71.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z71.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z71.object({startDate:z71.string().optional(),endDate:z71.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z71.coerce.number().int().positive().default(1),limit:z71.coerce.number().int().positive().max(100).default(20),sortBy:z71.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z71.string().optional(),activeOnly:z71.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z71.object({totalCredits:z71.number(),totalCostUsd:z71.number(),totalMessages:z71.number(),avgCostPerMessage:z71.number(),avgCreditsPerMessage:z71.number(),periodStart:z71.string(),periodEnd:z71.string(),creditsChange:z71.number().nullable(),costChange:z71.number().nullable(),messagesChange:z71.number().nullable(),unattributedCredits:z71.number(),unattributedCostUsd:z71.number(),unattributedMessages:z71.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z71.object({date:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z71.object({organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number(),projectCount:z71.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z71.object({userId:z71.string(),userName:z71.string().nullable(),userEmail:z71.string().nullable(),userImage:z71.string().nullable(),organizationId:z71.string().nullable(),organizationName:z71.string().nullable(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),projectCount:z71.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z71.object({projectId:z71.string(),projectName:z71.string(),projectDisplayName:z71.string().nullable(),organizationId:z71.string(),organizationName:z71.string(),credits:z71.number(),costUsd:z71.number(),messages:z71.number(),percentage:z71.number(),userCount:z71.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z71.object({id:z71.string(),name:z71.string(),value:z71.number(),percentage:z71.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z71.object({day:z71.number(),hour:z71.number(),value:z71.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z71.object({summary:UsageOverviewSummaryDTOSchema,timeline:z71.array(UsageTimelinePointDTOSchema),topOrganizations:z71.array(OrganizationUsageRowDTOSchema),topUsers:z71.array(UserUsageRowDTOSchema),topProjects:z71.array(ProjectUsageRowDTOSchema),creditDistribution:z71.array(UsageDistributionItemDTOSchema),userDistribution:z71.array(UsageDistributionItemDTOSchema),heatmap:z71.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z71.object({page:z71.number(),limit:z71.number(),totalItems:z71.number(),totalPages:z71.number(),hasMore:z71.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z71.object({organizations:z71.array(OrganizationUsageRowDTOSchema),top:z71.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z71.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z71.object({users:z71.array(ExtendedUserUsageRowDTOSchema),top:z71.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z71.object({projects:z71.array(ExtendedProjectUsageRowDTOSchema),top:z71.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z71.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z71.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z71.object({credits:z71.number(),costUsd:z71.number(),messages:z71.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),createdAt:z71.string(),memberCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z71.object({id:z71.string(),name:z71.string().nullable(),email:z71.string(),image:z71.string().nullable(),createdAt:z71.string(),organizationCount:z71.number(),projectCount:z71.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z71.object({id:z71.string(),name:z71.string(),displayName:z71.string().nullable(),createdAt:z71.string(),organizationId:z71.string(),organizationName:z71.string(),ownerId:z71.string(),ownerName:z71.string().nullable(),ownerEmail:z71.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z71.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z72}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z72.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z72.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z72.object({command:z72.string().min(1).max(1e4),cwd:z72.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z72.record(z72.string(),z72.string()).optional(),name:z72.string().optional(),waitForCompletion:z72.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=z72.object({identifier:z72.string(),status:SandboxProcessStatusSchema,command:z72.string().optional(),startedAt:z72.string().optional(),exitCode:z72.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z72.object({processes:z72.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z72.object({processId:z72.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z72.object({success:z72.boolean(),message:z72.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z73}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_asset_reading();init_env();init_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_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_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&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path: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&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.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&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,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&&params.set("includeDeleted","true"),opts.includeAgentBranches&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff${qs?`?${qs}`:""}`)).data}async getBranchStatus(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/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&&params.set("agent_name",opts.agentName),opts.branch&&params.set("env",opts.branch),opts.status&&params.set("status",opts.status),opts.page!==void 0&&params.set("page",String(opts.page)),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)}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&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&&params.set("noRestart","true"),options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),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,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&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path: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&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId,request={}){return(await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null}async listPublications(projectId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications${search?`?${search}`:""}`)).data}async getPublication(projectId,publicationId){return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}`)).data}async getPublicationLogs(projectId,publicationId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit));let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/publications/${encodeURIComponent(publicationId)}/logs${search?`?${search}`:""}`)).data}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.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&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,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&&params.set("includeDeleted","true"),opts.includeAgentBranches&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeURIComponent(branch)}/diff${qs?`?${qs}`:""}`)).data}async getBranchStatus(projectId,branch,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/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&&params.set("agent_name",opts.agentName),opts.branch&&params.set("env",opts.branch),opts.status&&params.set("status",opts.status),opts.page!==void 0&&params.set("page",String(opts.page)),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)}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&&params.set("limit",String(query.limit)),query.before&&params.set("before",query.before);let search=params.toString();return(await this.request(`/api/management/projects/${projectId}/branches/${encodeBranchPathSegment(branch)}/sandbox/logs${search?`?${search}`:""}`)).data}async sandboxPull(projectId,onProgress,branch,options={}){let params=new URLSearchParams;options.noRestart&&params.set("noRestart","true"),options.wait!==void 0&&params.set("wait",String(options.wait));let search=params.toString(),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
- `);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&&params.set("base",opts.base),opts?.max!==void 0&&params.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 deleteAsset(projectId,id){return(await this.request(this.tenantPath(projectId,`/assets/${id}`),{method:"DELETE"})).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(`
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&&params.set("base",opts.base),opts?.max!==void 0&&params.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
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(`
68
69
  `)?indentComment(comment,indent):comment.includes(`
69
70
  `)?`
@@ -271,7 +272,7 @@ ${a}${o}
271
272
  `}case"submit":{let o=n?` ${t("dim",n)}`:"",c2=i?t("gray",d2):"";return`${s}${c2}${o}`}case"cancel":{let o=n?` ${t(["strikethrough","dim"],n)}`:"",c2=i?t("gray",d2):"";return`${s}${c2}${o}${n.trim()?`
272
273
  ${c2}`:""}`}default:{let o=i?`${t("cyan",d2)} `:"",c2=i?t("cyan",E2):"";return`${s}${o}${u2}
273
274
  ${c2}
274
- `}}}}).prompt(),"Ot")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}var init_interactive=__esm({"src/cli/utils/interactive.ts"(){init_dist();__name(isInteractive,"isInteractive");__name(assertInteractive,"assertInteractive")}});import fs14 from"node:fs";import path16 from"node:path";function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiBaseUrl}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl,...tenantApiBaseUrl?{tenantApiBaseUrl}:{}},layout=resolveProjectLayoutPaths(targetDir),projectPath=path16.join(targetDir,layout.project);fs14.mkdirSync(path16.dirname(projectPath),{recursive:!0}),writeIfChanged(projectPath,`${JSON.stringify(fimoJson,null,2)}
275
+ `}}}}).prompt(),"Ot")}});function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}var init_interactive=__esm({"src/cli/utils/interactive.ts"(){init_dist();__name(isInteractive,"isInteractive");__name(assertInteractive,"assertInteractive")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});import fs14 from"node:fs";import path16 from"node:path";function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiBaseUrl}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl,...tenantApiBaseUrl?{tenantApiBaseUrl}:{}},layout=resolveProjectLayoutPaths(targetDir),projectPath=path16.join(targetDir,layout.project);fs14.mkdirSync(path16.dirname(projectPath),{recursive:!0}),writeIfChanged(projectPath,`${JSON.stringify(fimoJson,null,2)}
275
276
  `)}function seedSiteName(args){let{targetDir,project}=args,configPath=resolveProjectConfigPath(targetDir);if(fs14.existsSync(configPath))try{let original=fs14.readFileSync(configPath,"utf-8"),config=JSON.parse(original),seo=config.seo??{};if(!(typeof seo.siteName=="string"?seo.siteName:"").trim()){let initialSiteName=project.displayName?.trim()||project.name;config.seo={...seo,siteName:initialSiteName},writeIfChanged(configPath,`${JSON.stringify(config,null,2)}
276
277
  `)}}catch{}}function writeIfChanged(filePath,content2){fs14.existsSync(filePath)&&fs14.readFileSync(filePath,"utf-8")===content2||fs14.writeFileSync(filePath,content2)}var init_local_project_files=__esm({"src/cli/utils/local-project-files.ts"(){init_project();__name(writeLocalProjectFiles,"writeLocalProjectFiles");__name(seedSiteName,"seedSiteName");__name(writeIfChanged,"writeIfChanged")}});function slugifyName(input){return input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var init_slug=__esm({"src/cli/utils/slug.ts"(){__name(slugifyName,"slugifyName")}});import fs15 from"node:fs";import path17 from"node:path";function defaultDirectoryName(project){let source=project.displayName?.trim()||project.name||project.id;return slugifyName(source)||project.id}function explainCloneRemoteError(error){return error instanceof ApiRequestError&&error.status===403?"Only users with manage access to this project can clone it locally.":error instanceof ApiRequestError&&error.status===404?"Project or Branch not found.":error instanceof Error?error.message:String(error)}function chooseCloneBranch(branches,requested){return requested?branches.find(row2=>branchNameOf(row2)===requested)??null:branches.find(row2=>branchNameOf(row2)===DEFAULT_BRANCH)??branches[0]??null}function projectFallback(projectId){return{id:projectId,name:projectId,displayName:null,organizationId:null}}function isNotFound(error){return error instanceof ApiRequestError&&error.status===404}async function selectProjectId(args){if(currentMode().format==="json")return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint:PICKER_HINT};if(!isInteractive())return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint:PICKER_HINT};if(!args.activeOrganizationId)return{status:"error",code:"NO_ORGANIZATION_SPECIFIED",message:"No active organization set.",hint:"Run `fimo orgs switch`, or pass a project ID explicitly."};let listSp=spinner("Loading projects"),projects2;try{projects2=await args.api.listProjects(args.activeOrganizationId),listSp.succeed("Projects loaded")}catch(error){return listSp.fail("Could not load projects"),{status:"error",code:"PROJECT_LIST_FAILED",message:error instanceof Error?error.message:String(error)}}if(projects2.length===0)return{status:"empty",message:"No projects in the active organization yet."};let selected=await _t({message:args.message??"Select a project to clone",options:projects2.map(project=>({value:project.id,label:project.displayName??project.name,hint:project.id}))});return q(selected)?{status:"cancelled"}:{status:"selected",projectId:selected}}function projectNotFound(projectId,apiUrl){return{ok:!1,code:"PROJECT_NOT_FOUND",message:`Project ${projectId} was not found on ${apiUrl}.`,hint:"Check `fimo projects list`, or set FIMO_API_URL to the backend that owns this project."}}async function resolveRemote(args){let{api,projectId,requestedBranch,apiUrl}=args,firstBranch=requestedBranch??DEFAULT_BRANCH;try{return{ok:!0,branch:firstBranch,remote:await api.withBranch(firstBranch).getGitRemote(projectId,firstBranch)}}catch(firstError){if(requestedBranch||!isNotFound(firstError))throw firstError;let branches;try{branches=await api.listBranches(projectId)}catch(listError){if(isNotFound(listError))return projectNotFound(projectId,apiUrl);throw firstError}let fallback=chooseCloneBranch(branches,void 0);if(!fallback)return{ok:!1,code:"NO_CLONEABLE_ENVS",message:"This project does not have any cloneable Branches.",hint:"Create a Branch before cloning this project."};let fallbackBranch=branchNameOf(fallback);if(fallbackBranch===firstBranch)throw firstError;return{ok:!0,branch:fallbackBranch,remote:await api.withBranch(fallbackBranch).getGitRemote(projectId,fallbackBranch)}}}async function cloneProject(args){let{api,cfg,projectId,dir,branch:requestedBranch}=args,remoteSp=spinner("Checking access and fetching git remote"),remote,branch;try{let resolved=await resolveRemote({api,projectId,requestedBranch,apiUrl:cfg.apiUrl});if(!resolved.ok)throw remoteSp.fail("Could not fetch git remote"),new CloneError(resolved.code,resolved.message,resolved.hint);({remote,branch}=resolved),remoteSp.succeed(`Remote ready (branch ${remote.branch})`)}catch(error){throw error instanceof CloneError?error:(remoteSp.fail("Could not fetch git remote"),new CloneError(error instanceof ApiRequestError&&error.status===403?"PROJECT_MANAGE_REQUIRED":"CLONE_FAILED",explainCloneRemoteError(error)))}let project=projectFallback(projectId),projectSp=spinner("Loading project details");try{project=await api.getProject(projectId),projectSp.succeed(`Project loaded (${project.displayName??project.name})`)}catch{projectSp.succeed("Project metadata unavailable; using project ID locally")}let targetDir=path17.resolve(dir??defaultDirectoryName(project));if(fs15.existsSync(targetDir)&&fs15.readdirSync(targetDir).length>0){let name=path17.basename(targetDir);throw new CloneError("DIRECTORY_NOT_EMPTY",`The folder "${name}" already exists and isn't empty.`,`Pick a different directory (e.g. \`fimo clone ${projectId} <dir>\`), or empty "${name}" first.`)}let relativeTarget=path17.relative(process.cwd(),targetDir)||".";if(!await remoteHasBranch(remote.url,remote.branch))throw new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Run `fimo init --project-id <id>` to scaffold and push it, or `fimo deploy` from an existing checkout.",{project,remote,branch,targetDir,relativeTarget});let cloneSp=spinner(`Cloning ${remote.branch} into ${targetDir}`);try{await cloneRepo({url:remote.url,branch:remote.branch,targetDir}),cloneSp.succeed("Repository cloned")}catch(error){throw cloneSp.fail("Git clone failed"),isMissingRemoteBranch(error)?new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Deploy the project once (`fimo deploy` from the source checkout, or from Fimo), then clone again."):new CloneError("GIT_CLONE_FAILED",error instanceof Error?error.message:String(error))}let linkSp=spinner("Linking local project");try{let{cleanUrl}=planRemoteConfig(remote.url);await runGit(["remote","set-url","origin",cleanUrl],targetDir).catch(()=>{}),await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl}),linkSp.succeed("Local project linked")}catch(error){throw linkSp.fail("Local project link failed"),new CloneError("PROJECT_LINK_FAILED",error instanceof Error?error.message:String(error))}return{project,branch,gitBranch:remote.branch,targetDir,relativeTarget}}async function cloneCommand(projectIdArg,dirArg,options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),api=new FimoApiClient(cfg),projectId=projectIdArg;if(!projectId){let picked=await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id});switch(picked.status){case"selected":projectId=picked.projectId;break;case"cancelled":ui.info({command:"clone",message:"Cancelled."});return;case"empty":ui.info({command:"clone",message:picked.message});return;case"error":ui.error({command:"clone",code:picked.code,message:picked.message,...picked.hint?{hint:picked.hint}:{}});return}}currentMode().format==="pretty"&&mt(`Cloning Fimo project ${projectId}`);let result;try{result=await cloneProject({api,cfg,projectId,dir:dirArg,branch:selectBranchOption(options)})}catch(error){if(error instanceof CloneError){ui.error({command:"clone",code:error.code,message:error.message,hint:error.hint});return}throw error}let{project,branch,gitBranch,targetDir,relativeTarget}=result;ui.ok({command:"clone",headline:`Project ${project.displayName??project.name} cloned.`,details:{project_id:project.id,project_name:project.name,display_name:project.displayName,organization_id:project.organizationId,env:branch,branch:gitBranch,target_dir:targetDir,relative_dir:relativeTarget},hint:`cd ${relativeTarget}`})}var CloneError,PICKER_HINT,init_clone=__esm({"src/cli/commands/clone.ts"(){init_dist5();init_esm();init_dist();init_api();init_auth();init_config();init_branch_option();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_slug();CloneError=class extends Error{static{__name(this,"CloneError")}code;hint;emptyRemote;constructor(code2,message,hint,emptyRemote){super(message),this.name="CloneError",this.code=code2,this.hint=hint,this.emptyRemote=emptyRemote}};__name(defaultDirectoryName,"defaultDirectoryName");__name(explainCloneRemoteError,"explainCloneRemoteError");__name(chooseCloneBranch,"chooseCloneBranch");__name(projectFallback,"projectFallback");__name(isNotFound,"isNotFound");PICKER_HINT="Pass a project ID explicitly, e.g. `fimo clone <projectId>`.";__name(selectProjectId,"selectProjectId");__name(projectNotFound,"projectNotFound");__name(resolveRemote,"resolveRemote");__name(cloneProject,"cloneProject");__name(cloneCommand,"cloneCommand")}});import path18 from"node:path";function remoteRef(remoteBranch){return`refs/remotes/fimo/${remoteBranch}`}async function remoteHeadOrNull(cwd,remoteBranch){try{return await runGit(["rev-parse","--verify",remoteRef(remoteBranch)],cwd)}catch{return null}}function relationFromCounts(ahead,behind){return ahead===0&&behind===0?"in-sync":ahead>0&&behind===0?"ahead":ahead===0&&behind>0?"behind":"diverged"}async function inspectBranchCheckout(args){args.fetch!==!1&&await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd);let[localBranch,localHead,remoteHead]=await Promise.all([currentBranch(args.cwd),runGit(["rev-parse","HEAD"],args.cwd),remoteHeadOrNull(args.cwd,args.remoteBranch)]);if(!remoteHead)return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead:null,ahead:0,behind:0,relation:"missing-remote"};let counts=await runGit(["rev-list","--left-right","--count",`HEAD...${remoteRef(args.remoteBranch)}`],args.cwd),[ahead=0,behind=0]=counts.split(/\s+/).map(Number);return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead,ahead,behind,relation:relationFromCounts(ahead,behind)}}async function hasPathChanges(cwd,filePath){let relativePath=path18.relative(cwd,filePath);return(await runGit(["status","--porcelain","--",relativePath],cwd)).length>0}function assertLocaleMutationState(state){if(state.localBranch!==state.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`The selected environment uses branch '${state.remoteBranch}', but the checkout is on '${state.localBranch}'.`,`Switch to '${state.remoteBranch}' before changing its locales.`);if(state.relation==="missing-remote")throw new BranchCheckoutError("ENV_REMOTE_MISSING",`The environment branch 'fimo/${state.remoteBranch}' does not exist yet.`,"Deploy the project before changing its locale lifecycle.");if(state.relation==="ahead")throw new BranchCheckoutError("ENV_BRANCH_AHEAD",`The local branch is ${state.ahead} commit${state.ahead===1?"":"s"} ahead of fimo/${state.remoteBranch}.`,"Deploy those commits first, then run the locale command again.");if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local branch and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before changing the environment locales.")}async function planLocaleMutationCheckout(args){let state=await inspectBranchCheckout(args);if(assertLocaleMutationState(state),await hasPathChanges(args.cwd,args.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config has uncommitted changes.","Commit, discard, or deploy the config change before changing locales.");if(state.relation==="behind"&&await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes, then run the locale command again.");return{cwd:args.cwd,configPath:args.configPath,state}}async function applyLocaleMutationCheckoutPlan(plan){let current=await inspectBranchCheckout({cwd:plan.cwd,remoteBranch:plan.state.remoteBranch,fetch:!1});if(current.localBranch!==plan.state.localBranch||current.localHead!==plan.state.localHead||current.remoteHead!==plan.state.remoteHead)throw new BranchCheckoutError("ENV_CHECKOUT_CHANGED","The checkout changed after the locale operation was reviewed.","Review the current Git state and run the locale command again.");if(assertLocaleMutationState(current),await hasPathChanges(plan.cwd,plan.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config changed after the locale operation was reviewed.","Commit, discard, or deploy the config change, then run the locale command again.");if(current.relation==="behind"){if(await hasUncommittedChanges(plan.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${current.remoteBranch} and now has uncommitted changes.`,"Stash the changes, then run the locale command again.");await runGit(["merge","--ff-only",remoteRef(current.remoteBranch)],plan.cwd)}}function recoveryCommands(remoteBranch,localBranch,relation){let inspect=`git log --oneline --left-right HEAD...fimo/${remoteBranch}`;return[...localBranch&&localBranch!==remoteBranch?[`git switch ${remoteBranch}`]:[],"git status","git fetch fimo",...relation==="ahead"||relation==="diverged"?[inspect]:[`git merge --ff-only fimo/${remoteBranch}`]]}async function synchronizeLocaleMutationCheckout(args){let state;try{state=await inspectBranchCheckout(args)}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(args.remoteBranch)}}if(state.localBranch!==state.remoteBranch)return{status:"required",reason:`The checkout moved to '${state.localBranch}' after the remote locale change.`,recovery:recoveryCommands(state.remoteBranch,state.localBranch,state.relation)};if(state.relation==="in-sync")return{status:"synchronized"};if(state.relation!=="behind")return{status:"required",reason:`The local branch is ${state.relation} relative to fimo/${state.remoteBranch}.`,recovery:recoveryCommands(state.remoteBranch,void 0,state.relation)};try{return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),{status:"synchronized"}}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(state.remoteBranch)}}}async function prepareDeployCheckout(args){let localBranch=await currentBranch(args.cwd);if(localBranch!==args.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`Deploy requires branch '${args.remoteBranch}'; checkout is on '${localBranch}'.`,`Run 'fimo checkout ${args.remoteBranch}'.`);let state=await inspectBranchCheckout(args);if(state.relation==="missing-remote")return"missing-remote";if(state.relation==="in-sync"||state.relation==="ahead")return"ready";if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before deploying.");if(await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes before deploying.");return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),"ready"}var BranchCheckoutError,init_branch_checkout=__esm({"src/cli/utils/branch-checkout.ts"(){init_git();BranchCheckoutError=class extends Error{constructor(code2,message,hint){super(message);this.code=code2;this.hint=hint;this.name="BranchCheckoutError"}static{__name(this,"BranchCheckoutError")}};__name(remoteRef,"remoteRef");__name(remoteHeadOrNull,"remoteHeadOrNull");__name(relationFromCounts,"relationFromCounts");__name(inspectBranchCheckout,"inspectBranchCheckout");__name(hasPathChanges,"hasPathChanges");__name(assertLocaleMutationState,"assertLocaleMutationState");__name(planLocaleMutationCheckout,"planLocaleMutationCheckout");__name(applyLocaleMutationCheckoutPlan,"applyLocaleMutationCheckoutPlan");__name(recoveryCommands,"recoveryCommands");__name(synchronizeLocaleMutationCheckout,"synchronizeLocaleMutationCheckout");__name(prepareDeployCheckout,"prepareDeployCheckout")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject2(subject){return typeof subject=="object"&&subject!==null}__name(isObject2,"isObject");function toArray2(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray2,"toArray");function extend(target,source){var index2,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index2=0,length=sourceKeys.length;index2<length;index2+=1)key=sourceKeys[index2],target[key]=source[key];return target}__name(extend,"extend");function repeat(string,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string;return result}__name(repeat,"repeat");function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject2;module2.exports.toArray=toArray2;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end2,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
277
278
  \x85\u2028\u2029`.indexOf(this.buffer.charAt(start-1))===-1;)if(start-=1,this.position-start>maxLength/2-1){head=" ... ",start+=5;break}for(tail="",end2=this.position;end2<this.buffer.length&&`\0\r
@@ -372,7 +373,7 @@ return __eta.res;
372
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(`
373
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,`
374
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={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse6,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse6,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile2,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(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(`
375
- `)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo-next"},{suffix:".client.ts",runtimeImport:"fimo-next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo-sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(requiredFormEntries,"requiredFormEntries");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z81}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?"fimo-next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo-next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo-next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo-sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let 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 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
377
  - ${errors.join(`
377
378
  - `)}
378
379
  No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
@@ -385,7 +386,7 @@ ${imports}
385
386
  export const content = {
386
387
  ${entries2}
387
388
  } as const;
388
- `}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function collectFieldRuntimeTypeImports(field,imports){if(!field||typeof field!="object"||Array.isArray(field))return;let definition=field;switch(definition.type){case"boolean":imports.add("FimoBoolean");return;case"media":imports.add("FimoMedia");return;case"reference":imports.add(Array.isArray(definition.targets)&&definition.targets.length>0?"FimoPolymorphicReference":"FimoReference");return;case"richtext":imports.add("FimoRichText"),imports.add("FimoRichTextContent");return;case"blocks":{let schema=definition.schema;if(!schema||typeof schema!="object"||Array.isArray(schema))return;let blockSchema=schema,fieldGroups=Array.isArray(blockSchema.oneOf)?blockSchema.oneOf.map(variant=>variant&&typeof variant=="object"&&!Array.isArray(variant)?variant.fields:void 0):[blockSchema.fields];for(let fields of fieldGroups)if(!(!fields||typeof fields!="object"||Array.isArray(fields)))for(let nestedField of Object.values(fields))collectFieldRuntimeTypeImports(nestedField,imports);return}default:return}}function runtimeTypeImportsFor(fields){let imports=new Set(["Fields","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"]);for(let field of Object.values(fields))collectFieldRuntimeTypeImports(field,imports);return RUNTIME_TYPE_IMPORT_ORDER.filter(typeImport=>imports.has(typeImport))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields),runtimeTypeImports:runtimeTypeImportsFor(fields)}}function syncSchemas(options){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=runtime?contentRuntimeImportFor(options.framework,runtime):"fimo-react",generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,RUNTIME_TYPE_IMPORT_ORDER,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z81.object({uid:z81.string().min(1),name:z81.string().min(1).optional(),isSingleton:z81.boolean().optional(),i18n:z81.object({enabled:z81.boolean().optional()}).optional(),groups:z81.array(z81.object({id:z81.string().min(1),label:z81.string().min(1),default:z81.boolean().optional()}).strict()).optional(),fields:z81.record(z81.string(),z81.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(readProjectPackage,"readProjectPackage");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(collectFieldRuntimeTypeImports,"collectFieldRuntimeTypeImports");__name(runtimeTypeImportsFor,"runtimeTypeImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
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=z82.object({uid:z82.string().min(1),name:z82.string().min(1).optional(),isSingleton:z82.boolean().optional(),i18n:z82.object({enabled:z82.boolean().optional()}).optional(),groups:z82.array(z82.object({id:z82.string().min(1),label:z82.string().min(1),default:z82.boolean().optional()}).strict()).optional(),fields:z82.record(z82.string(),z82.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(`
389
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(`
390
391
  `);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
391
392
  `);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
@@ -1185,7 +1186,7 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
1185
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(`
1186
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)}
1187
1188
 
1188
- ${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 z74}from"zod";var CapabilityTokenSchema=z74.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=z74.array(CapabilityTokenSchema);import{z as z75}from"zod";var CronTriggerSchema=z75.object({type:z75.literal("schedule"),cron:z75.string().min(1,"cron expression required"),tz:z75.string().optional()}),ManualTriggerSchema2=z75.object({type:z75.literal("manual")}),WebhookTriggerSchema2=z75.object({type:z75.literal("webhook"),path:z75.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z75.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z75.object({name:z75.string().min(1),capability_grant:z75.enum(["inherit","explicit"]).optional(),explicit_grants:z75.array(z75.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=z75.object({"sub-agents":z75.array(SubAgentRefSchema)}),RuntimeConfigSchema=z75.object({cloud:z75.boolean().optional(),dev:z75.boolean().optional(),long_running:z75.boolean().optional()}),DataSourceSchema=z75.enum(["main","prod"]),ConfigValueKeySchema=z75.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=z75.preprocess(value=>typeof value=="string"?{key:value}:value,z75.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z75.boolean().default(!0),delivery:z75.literal("process_env").default("process_env")})),IntegrationKeySchema=z75.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z75.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=z75.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z75.object({enabled:z75.boolean().default(!0),tools:z75.record(IntegrationToolKeySchema,z75.boolean()).optional()})),IntegrationPolicySchema=z75.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z75.object({version:z75.literal(1),description:z75.string().min(1).max(280).optional(),model:z75.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z75.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z75.array(DataSourceSchema).optional(),secrets:z75.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 z76}from"zod";var SurfaceGuardPolicySchema=z76.enum(["block","warn","allow"]),ClassificationSchema=z76.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z76.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z76.object({enabled:z76.boolean(),allowed_skills:z76.array(z76.string().min(1)).default([]),allowed_classifications:z76.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z76.enum(["off","daily","weekly"]),NotificationFormatSchema=z76.object({markdown:z76.boolean().default(!0),html:z76.boolean().default(!1)}),NotificationsPolicySchema=z76.object({email_recipients:z76.array(z76.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z76.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z76.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 z77}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=z77.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z77.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 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
1190
  ${line}`):next2=(content2.endsWith(`
1190
1191
  `)?content2:content2+`
1191
1192
  `)+line+`
@@ -1202,9 +1203,9 @@ Full report: fimo agents report ${target.agentName} --session ${target.sessionId
1202
1203
  ${result.driftLines.map(l=>` ${l}`).join(`
1203
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(`
1204
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(`
1205
- `)}__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_dist();import fs12 from"node:fs";import path14 from"node:path";import{z as z78}from"zod";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z78.object({sourceId:z78.string().min(1),path:z78.string().min(1),name:z78.string().min(1).optional(),parentId:z78.string().min(1).optional(),folderPath:z78.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z78.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 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
1207
  ${issues.join(`
1207
- `)}`)}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");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_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.";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
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",`
1209
1210
  Examples:
1210
1211
  fimo integrations connect slack
@@ -1222,7 +1223,7 @@ Fix: add a route entry to ${configDisplayPath} "routes" with a matching "path".`
1222
1223
  Fix: add the route to src/routes.ts. Example: route('${route.path.replace(/^\//,"")}', './pages/YourPage.tsx')`);i18n.routingStrategy==="path-prefix"&&i18n.locales.length>1&&errors.push(...validateLocaleRouteCollisions({configRoutes,fileRoutes,i18n,configDisplayPath,routesSourceUsesLegacyHelper:sourceUsesLegacyFimoRoutes(routesFilePath)}));let routeById=new Map;for(let route of configRoutes){if(routeById.has(route.id)){let previousPath=routeById.get(route.id).path;errors.push(`Duplicate route id "${route.id}" found for paths "${previousPath}" and "${route.path}".`);continue}routeById.set(route.id,route)}for(let route of configRoutes){for(let issue of route.contract.issues)errors.push(`Route "${route.id}" (${route.path}): ${issue.message}
1223
1224
  Fix: ${issue.fix}`);errors.push(...validatePageSources(route))}errors.push(...validateRouteShapeCollisions(configRoutes));for(let route of configRoutes){let file=registrablePaths(route).map(candidate=>pathToFile.get(candidate)).find(Boolean);if(!file)continue;let routeModulePath=path24.resolve(srcDir,file);if(!fs21.existsSync(routeModulePath)){errors.push(`Route "${route.id}" (${route.path}) references missing module "${file}".
1224
1225
  Fix: create the file at src/${file}.`);continue}if(route.seo){let GLOBAL_VARIABLES=new Set(["siteName","label"]),seoFields=[{name:"title",value:route.seo.title},{name:"description",value:route.seo.description}];for(let field of seoFields){if(typeof field.value!="string")continue;let templatePattern=/\{\{([^}]+)\}\}/g,match;for(;(match=templatePattern.exec(field.value))!==null;){let variable=match[1].trim();if(GLOBAL_VARIABLES.has(variable))continue;let entryParamNames=route.contract.entryParams.map(param=>param.name),availableParams=entryParamNames.length>0?entryParamNames.join(", "):"none";if(variable.includes(".")){let paramKey=variable.split(".")[0];entryParamNames.includes(paramKey)||errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" but "${paramKey}" is not a declared entry param. Available params: ${availableParams}.`)}else errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" which is not a global variable (siteName, label) and not a dotted param reference (e.g., "{{param.field}}"). Available params: ${availableParams}.`)}}}}return{errors,routesChecked:configRoutes.length}}__name(validateRouteMetadata,"validateRouteMetadata");function validatePageSources(route){if(!route.sources)return[];let errors=[],entryParamNames=new Set(route.contract.entryParams.map(param=>param.name));for(let[sourceName,rawSource]of Object.entries(route.sources)){if(!/^[A-Za-z][\w-]*$/.test(sourceName)||!isRecord2(rawSource)){errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" is not a valid named source.`);continue}if(rawSource.type==="labels"){let match=rawSource.match;(!Array.isArray(match)||match.length===0||match.some(pattern=>{if(typeof pattern!="string")return!0;let wildcard=pattern.indexOf("*");return wildcard!==-1&&!(pattern.length>2&&pattern.endsWith(".*")&&wildcard===pattern.length-1)}))&&errors.push(`Route "${route.id}" (${route.path}): Labels source "${sourceName}" needs exact keys or prefixes ending in .*.`);continue}if(rawSource.type!=="single"&&rawSource.type!=="collection"){errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" type must be labels, single, or collection.`);continue}if((typeof rawSource.schema!="string"||!rawSource.schema)&&errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" needs a schema.`),rawSource.type==="collection"&&rawSource.query!==void 0&&!isRecord2(rawSource.query)){errors.push(`Route "${route.id}" (${route.path}): Collection source "${sourceName}" query must be an object.`);continue}for(let expression of pageSourceParamExpressions(rawSource.query)){let param=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/.exec(expression)?.[1];(!param||!entryParamNames.has(param))&&errors.push(`Route "${route.id}" (${route.path}): source "${sourceName}" references undeclared param "${param??expression}". Fix: use $params.<declared-entry-param>.<field>.`)}}return errors}__name(validatePageSources,"validatePageSources");function validateI18nConfig(config){let rawI18n=isRecord2(config.i18n)?config.i18n:{},errors=[],rawDefaultLocale=typeof rawI18n.defaultLocale=="string"?rawI18n.defaultLocale:"en",defaultLocale=normalizeFimoLocale(rawDefaultLocale);defaultLocale||errors.push(`Invalid i18n.defaultLocale "${rawDefaultLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);let rawLocales=Array.isArray(rawI18n.locales)?rawI18n.locales:defaultLocale?[defaultLocale]:[];rawI18n.locales!==void 0&&!Array.isArray(rawI18n.locales)&&errors.push("i18n.locales must be an array of locale strings.");let locales=[],seenLocales=new Set;for(let rawLocale of rawLocales){if(typeof rawLocale!="string"){errors.push(`Invalid i18n.locales entry ${JSON.stringify(rawLocale)}. Locale entries must be strings.`);continue}let locale=normalizeFimoLocale(rawLocale);if(!locale){errors.push(`Invalid i18n.locales entry "${rawLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);continue}seenLocales.has(locale)||(seenLocales.add(locale),locales.push(locale))}let effectiveDefaultLocale=defaultLocale??"en";seenLocales.has(effectiveDefaultLocale)||(errors.push(`i18n.locales must include i18n.defaultLocale "${effectiveDefaultLocale}".`),locales.unshift(effectiveDefaultLocale));let rawRouting=isRecord2(rawI18n.routing)?rawI18n.routing:{},routingStrategy=typeof rawRouting.strategy=="string"?rawRouting.strategy:"path-prefix";return routingStrategy!=="path-prefix"&&errors.push(`Unsupported i18n.routing.strategy "${routingStrategy}". Supported now: "path-prefix".`),{defaultLocale:effectiveDefaultLocale,locales,routingStrategy,errors}}__name(validateI18nConfig,"validateI18nConfig");function validateRouteShapeCollisions(configRoutes){let errors=[],byShape=new Map;for(let route of configRoutes){let shape=route.contract.canonicalPath.split("/").map(segment=>segment.startsWith(":")?":param":segment).join("/"),previous=byShape.get(shape);if(previous&&(previous.contract.localeParam||route.contract.localeParam)){errors.push(`Routes "${previous.id}" (${previous.path}) and "${route.id}" (${route.path}) both answer "${route.contract.canonicalPath}".
1225
- Fix: keep one of them, or give them distinct paths \u2014 a locale segment does not make two routes distinct.`);continue}previous||byShape.set(shape,route)}return errors}__name(validateRouteShapeCollisions,"validateRouteShapeCollisions");function validateLocaleRouteCollisions(args){let errors=[],reservedPrefixes=new Set(args.i18n.locales.map(locale=>locale.toLowerCase()));for(let route of args.configRoutes){let first2=firstPathSegment(route.path);first2&&reservedPrefixes.has(first2.toLowerCase())&&errors.push(`Route "${route.id}" (${route.path}) uses reserved locale prefix "${first2}". Declare the locale as "/:locale/..." in ${args.configDisplayPath} and as ":locale?/..." in React Router so the default locale remains unprefixed.`)}if(!args.routesSourceUsesLegacyHelper)for(let route of args.fileRoutes){if(!route.path||route.isLayout)continue;let first2=firstPathSegment(route.path);first2&&normalizeLocaleSpelling(first2)===`:${FIMO_LOCALE_PARAM}`||(first2?.startsWith(":")||first2==="*")&&errors.push(`Route "${route.path}" is a top-level dynamic route in a multi-locale project. It can capture locale URLs like "/${args.i18n.locales[0]}". Put an explicit optional ":locale?" segment first in the React Router path, or keep this route outside the localized route boundary.`)}return errors}__name(validateLocaleRouteCollisions,"validateLocaleRouteCollisions");function sourceUsesLegacyFimoRoutes(routesFilePath){if(!fs21.existsSync(routesFilePath))return!1;let source=fs21.readFileSync(routesFilePath,"utf-8"),importedName=source.match(/import\s*\{(?<imports>[^}]*)\}\s*from\s*['"]fimo\/react-router\/routes['"]/s)?.groups?.imports?.split(",").map(specifier=>specifier.trim().match(/^fimoRoutes(?:\s+as\s+(?<alias>[A-Za-z_$][\w$]*))?$/)?.groups?.alias??(specifier.trim()==="fimoRoutes"?"fimoRoutes":null)).find(name=>!!name);return importedName?new RegExp(`\\b${importedName}\\s*\\(`).test(source):!1}__name(sourceUsesLegacyFimoRoutes,"sourceUsesLegacyFimoRoutes");function normalizeLocaleSpelling(routePath){return routePath.replace(`:${FIMO_LOCALE_PARAM}?`,`:${FIMO_LOCALE_PARAM}`)}__name(normalizeLocaleSpelling,"normalizeLocaleSpelling");function registrablePaths(route){let declared=normalizeLocaleSpelling(route.contract.path);return route.contract.localeParam?.optional?[declared,route.contract.canonicalPath]:[declared]}__name(registrablePaths,"registrablePaths");function firstPathSegment(routePath){return routePath.split("/").filter(Boolean)[0]??null}__name(firstPathSegment,"firstPathSegment");function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function normalizeFimoLocale(locale){let trimmed=locale?.trim();if(!trimmed)return null;let candidate=trimmed.replace(/_/g,"-");try{return Intl.getCanonicalLocales(candidate)[0]??null}catch{return null}}__name(normalizeFimoLocale,"normalizeFimoLocale");init_esm();import{existsSync as existsSync6,readFileSync as readFileSync6,readdirSync as readdirSync4}from"node:fs";import{basename as basename2,join as join7,resolve as resolve6}from"node:path";var SCHEMAS_REL2="src/schemas",FIELD_TYPES=new Set(FieldTypeSchema.options),RESERVED_FIELD_NAMES=new Set(RESERVED_CONTENT_FIELD_NAMES);function validateSchemas(options={}){let cwd=resolve6(options.cwd??process.cwd()),schemasDir=join7(cwd,SCHEMAS_REL2);if(!existsSync6(schemasDir))return{errors:[],schemasChecked:0};let files=readdirSync4(schemasDir).filter(f=>f.endsWith(".json")).sort(),errors=[],schemaUids=new Set;for(let fileName of files){let schema=readSchemaObject(join7(schemasDir,fileName));schema&&typeof schema.uid=="string"&&schemaUids.add(schema.uid)}for(let fileName of files){let file=join7(SCHEMAS_REL2,fileName);errors.push(...validateSchemaFile(join7(schemasDir,fileName),file,schemaUids))}return{errors,schemasChecked:files.length}}__name(validateSchemas,"validateSchemas");function readSchemaObject(absolutePath){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch{return null}return typeof schema=="object"&&schema!==null&&!Array.isArray(schema)?schema:null}__name(readSchemaObject,"readSchemaObject");function validateSchemaFile(absolutePath,file,schemaUids=new Set){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch(error){return[{rule:"schemas/parse",message:`Invalid JSON: ${error instanceof Error?error.message:String(error)}`,file}]}if(typeof schema!="object"||schema===null||Array.isArray(schema))return[{rule:"schemas/shape",message:"Schema must be a JSON object.",file}];let errors=[],{uid,name,fields,i18n,isSingleton,groups}=schema,expectedUid=basename2(file,".json");if(typeof uid!="string"||uid.length===0?errors.push({rule:"schemas/uid",message:`Missing "uid". Set it to the file name: "${expectedUid}".`,file}):uid!==expectedUid?errors.push({rule:"schemas/uid",message:`"uid" is "${uid}" but the file is ${expectedUid}.json \u2014 they must match.`,file}):CONTENT_TYPE_NAME_PATTERN.test(uid)||errors.push({rule:"schemas/type-name",message:`"uid" must use ${CONTENT_TYPE_NAME_PATTERN_DESCRIPTION}.`,file}),(typeof name!="string"||name.length===0)&&errors.push({rule:"schemas/name",message:'Missing "name" (the human-readable label).',file}),isSingleton!==void 0&&typeof isSingleton!="boolean"&&errors.push({rule:"schemas/singleton",message:'"isSingleton" must be a boolean when provided.',file}),i18n!==void 0)if(typeof i18n!="object"||i18n===null||Array.isArray(i18n))errors.push({rule:"schemas/i18n",message:'"i18n" must be an object like { "enabled": false }.',file});else{let keys=Object.keys(i18n);(keys.length!==1||keys[0]!=="enabled"||typeof i18n.enabled!="boolean")&&errors.push({rule:"schemas/i18n",message:'"i18n" only supports one boolean option: { "enabled": true | false }.',file})}let groupIds=new Set;if(groups!==void 0)if(!Array.isArray(groups))errors.push({rule:"schemas/groups",message:'"groups" must be an array.',file});else{let defaults=0;for(let[index2,group]of groups.entries()){let parsed=ContentFieldGroupSchema.safeParse(group);if(!parsed.success){errors.push({rule:"schemas/groups",message:`Group at index ${index2} is invalid: ${parsed.error.issues[0]?.message??"invalid group"}.`,file});continue}groupIds.has(parsed.data.id)&&errors.push({rule:"schemas/groups",message:`Group ID "${parsed.data.id}" is declared more than once.`,file}),groupIds.add(parsed.data.id),parsed.data.default&&(defaults+=1)}defaults>1&&errors.push({rule:"schemas/groups",message:"At most one group may be the default.",file})}if(typeof fields!="object"||fields===null||Array.isArray(fields))return errors.push({rule:"schemas/fields",message:'Missing "fields" object.',file}),errors;let parsedFields={};for(let[fieldName,definition]of Object.entries(fields)){if(!CONTENT_FIELD_NAME_PATTERN.test(fieldName)){errors.push({rule:"schemas/field-name",message:`Field "${fieldName}" must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`,file});continue}if(RESERVED_FIELD_NAMES.has(fieldName)){errors.push({rule:"schemas/reserved-field",message:`Field "${fieldName}" is reserved entry metadata \u2014 the platform manages it automatically. Remove it from the schema${fieldName==="slug"?" (set slug inside entry data on create instead)":""}.`,file});continue}if(typeof definition!="object"||definition===null||Array.isArray(definition)){errors.push({rule:"schemas/field-shape",message:`Field "${fieldName}" must be an object like { "type": "string" }.`,file});continue}let{type}=definition,memberships=Array.isArray(definition.group)?definition.group:definition.group===void 0?[]:[definition.group];new Set(memberships).size!==memberships.length&&errors.push({rule:"schemas/field-group",message:`Field "${fieldName}" lists the same group more than once.`,file});for(let membership of memberships)(typeof membership!="string"||!groupIds.has(membership))&&errors.push({rule:"schemas/field-group",message:`Field "${fieldName}" references unknown group "${String(membership)}".`,file});if((typeof type!="string"||!FIELD_TYPES.has(type))&&errors.push({rule:"schemas/field-type",message:`Field "${fieldName}" has unsupported type "${String(type)}". Allowed: ${[...FIELD_TYPES].join(", ")}.`,file}),"localized"in definition&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "localized" is not supported. Use "i18n": false to share one value across locales.`,file}),"i18n"in definition&&(typeof definition.i18n!="boolean"?errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" must be true or false.`,file}):type==="blocks"&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" is not supported on blocks fields.`,file})),type==="blocks"){let parsed2=ContentFieldDefinitionSchema.safeParse(definition);if(!parsed2.success){for(let issue of parsed2.error.issues)errors.push({rule:"schemas/structured-content-shape",message:`Field "${fieldName}"${issue.path.length>0?` at ${issue.path.join(".")}`:""}: ${issue.message}`,file});continue}parsedFields[fieldName]=parsed2.data,walkContentFields({[fieldName]:parsed2.data},({field,path:path53,structuredDepth,insideStructuredContent})=>{if(insideStructuredContent&&field.group!==void 0&&errors.push({rule:"schemas/field-group",message:`Field "${path53.join(".")}" cannot use "group" inside blocks.`,file}),field.type==="blocks"&&structuredDepth>=MAX_STRUCTURED_CONTENT_DEPTH&&errors.push({rule:"schemas/structured-content-depth",message:`Field "${path53.join(".")}" exceeds the ${MAX_STRUCTURED_CONTENT_DEPTH}-level blocks limit.`,file}),!(!insideStructuredContent||field.type!=="reference")){if(field.targets){errors.push({rule:"schemas/structured-content-reference",message:`Reference field "${path53.join(".")}" must use one fixed "target" inside blocks.`,file});return}field.target&&schemaUids.size>0&&!schemaUids.has(field.target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${path53.join(".")}" targets unknown schema "${field.target}".`,file})}});continue}let parsed=ContentFieldDefinitionSchema.safeParse(definition);if(parsed.success&&(parsedFields[fieldName]=parsed.data),type==="reference"){let{target,targets,many}=definition;if(targets!==void 0&&target!==void 0)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" declares both "target" and "targets" \u2014 a field is fixed or polymorphic, never both.`,file});else if(targets!==void 0){let targetList=Array.isArray(targets)?targets:null;if(!targetList||targetList.length===0||new Set(targetList).size!==targetList.length)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare "targets" as a non-empty array of unique content types.`,file});else for(let candidate of targetList)typeof candidate!="string"||!CONTENT_TYPE_NAME_PATTERN.test(candidate)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" has an invalid entry in "targets".`,file}):schemaUids.size>0&&!schemaUids.has(candidate)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${candidate}".`,file})}else typeof target!="string"||!CONTENT_TYPE_NAME_PATTERN.test(target)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare a valid "target" content type (or "targets" for a polymorphic field).`,file}):schemaUids.size>0&&!schemaUids.has(target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${target}".`,file});many!==void 0&&typeof many!="boolean"&&errors.push({rule:"schemas/reference-many",message:`Reference field "${fieldName}" must use a boolean "many" value.`,file})}else for(let referenceOnlyKey of["target","targets","many"])referenceOnlyKey in definition&&errors.push({rule:"schemas/reference-shape",message:`Field "${fieldName}": "${referenceOnlyKey}" is only supported on reference fields.`,file})}for(let problem of collectConditionProblems(parsedFields))errors.push({rule:"schemas/conditions",message:problem.message,file});return errors}__name(validateSchemaFile,"validateSchemaFile");init_api();init_config();init_auth_errors();init_project();import fs22 from"node:fs";import path25 from"node:path";var MIN_DB_LABELS_FIMO_VERSION="0.2.5",MIN_DB_LABELS_TEMPLATE_VERSION=4;function getDbLabelsRuntimeWarning(cwd){if(readExplicitConfigVersion(cwd)<MIN_DB_LABELS_TEMPLATE_VERSION)return null;let projectPackage=readPackageJson2(path25.join(cwd,"package.json")),fimoSpec=findFimoSpec(projectPackage);if(!fimoSpec)return buildWarning("package.json has no fimo dependency");let source=findRuntimeVersion(cwd,fimoSpec);return!source||!isVersionOlder(source.version,MIN_DB_LABELS_FIMO_VERSION)?null:buildWarning(`${source.label} is fimo@${source.version}`)}__name(getDbLabelsRuntimeWarning,"getDbLabelsRuntimeWarning");function readExplicitConfigVersion(cwd){try{let raw=JSON.parse(fs22.readFileSync(resolveProjectConfigPath(cwd),"utf8")),parsed=Number.parseInt(String(raw.version),10);return Number.isFinite(parsed)&&parsed>0?parsed:0}catch{return 0}}__name(readExplicitConfigVersion,"readExplicitConfigVersion");function buildWarning(subject){return[`CRITICAL: ${subject}, but DB-owned labels require fimo >= ${MIN_DB_LABELS_FIMO_VERSION}.`,"Labels changed with `fimo labels` or Fimo Studio may not render in this project until the app runtime is upgraded.","Run `npm install fimo@latest` (or your package manager equivalent), then run `fimo validate` again."].join(" ")}__name(buildWarning,"buildWarning");function findRuntimeVersion(cwd,fimoSpec){let installed=readPackageJson2(path25.join(cwd,"node_modules","fimo","package.json"));if(typeof installed?.version=="string")return{label:"installed node_modules/fimo",version:installed.version};let packageLockVersion=readPackageLockVersion(cwd);if(packageLockVersion)return{label:"package-lock.json",version:packageLockVersion};let exactSpecVersion=parseVersion2(fimoSpec);if(exactSpecVersion)return{label:"package.json dependency",version:exactSpecVersion.normalized};if(fimoSpec.startsWith("file:")){let fileVersion=readFileDependencyVersion(cwd,fimoSpec);if(fileVersion)return{label:"package.json file dependency target",version:fileVersion}}return null}__name(findRuntimeVersion,"findRuntimeVersion");function findFimoSpec(pkg){let dependenciesSpec=pkg?.dependencies?.fimo;if(typeof dependenciesSpec=="string"&&dependenciesSpec.trim())return dependenciesSpec.trim();let devDependenciesSpec=pkg?.devDependencies?.fimo;return typeof devDependenciesSpec=="string"&&devDependenciesSpec.trim()?devDependenciesSpec.trim():null}__name(findFimoSpec,"findFimoSpec");function readFileDependencyVersion(cwd,spec){let rawPath=spec.slice(5),packageRoot=path25.isAbsolute(rawPath)?rawPath:path25.resolve(cwd,rawPath),pkg=readPackageJson2(path25.join(packageRoot,"package.json"));return typeof pkg?.version=="string"?pkg.version:null}__name(readFileDependencyVersion,"readFileDependencyVersion");function readPackageLockVersion(cwd){try{let lock=JSON.parse(fs22.readFileSync(path25.join(cwd,"package-lock.json"),"utf8")),packagesVersion=lock.packages?.["node_modules/fimo"]?.version;if(typeof packagesVersion=="string")return packagesVersion;let dependencyVersion=lock.dependencies?.fimo?.version;return typeof dependencyVersion=="string"?dependencyVersion:null}catch{return null}}__name(readPackageLockVersion,"readPackageLockVersion");function readPackageJson2(filePath){try{return JSON.parse(fs22.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson2,"readPackageJson");function isVersionOlder(version,minimum){let parsed=parseVersion2(version),parsedMinimum=parseVersion2(minimum);if(!parsed||!parsedMinimum)return!1;for(let key of["major","minor","patch"]){if(parsed[key]<parsedMinimum[key])return!0;if(parsed[key]>parsedMinimum[key])return!1}return!1}__name(isVersionOlder,"isVersionOlder");function parseVersion2(version){let match=version.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return match?{major:Number(match[1]),minor:Number(match[2]),patch:Number(match[3]),normalized:`${Number(match[1])}.${Number(match[2])}.${Number(match[3])}`}:null}__name(parseVersion2,"parseVersion");import{execFile as execFile3}from"node:child_process";import fs23 from"node:fs";import path26 from"node:path";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3),LOCKFILE_MANAGERS2={"pnpm-lock.yaml":"pnpm","bun.lock":"bun","bun.lockb":"bun","yarn.lock":"yarn","package-lock.json":"npm"};async function inspectDependencyLifecycleScripts(cwd,execute=executeCommand){let selection=selectPackageManager(cwd);if(!selection)return{status:"warning",message:"Dependency lifecycle-script approval check skipped: no package manager could be selected from package.json or a lockfile."};if(!fs23.existsSync(path26.join(cwd,"node_modules")))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: ${selection.name} has no installed node_modules state to inspect.`};if(selection.name==="yarn")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: Yarn has no stable standalone blocked-script listing command."};if(selection.name==="npm")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: this npm version has no supported read-only blocked-script listing command."};try{let versionResult=await execute(selection.name,["--version"],cwd);if(selection.version&&!matchesRequestedVersion(versionResult.stdout,selection.version))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: the installed ${selection.name} version ${versionResult.stdout.trim()||"unknown"} does not match the exact packageManager pin ${selection.name}@${selection.version}.`};if(selection.name==="pnpm"&&!supportsPnpmIgnoredBuilds(versionResult.stdout))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: pnpm ${versionResult.stdout.trim()||"unknown"} does not support pnpm ignored-builds inspection (requires pnpm 10.1+).`};let args=selection.name==="pnpm"?["ignored-builds"]:["pm","untrusted"],result=await execute(selection.name,args,cwd);return selection.name==="pnpm"?parsePnpmIgnoredBuilds(result.stdout):parseBunUntrusted(result.stdout)}catch(error){return{status:"warning",message:`Dependency lifecycle-script approval check skipped: could not inspect ${selection.name} install state (${error instanceof Error?error.message:String(error)}).`}}}__name(inspectDependencyLifecycleScripts,"inspectDependencyLifecycleScripts");function parsePnpmIgnoredBuilds(output){let lines=output.split(/\r?\n/),section2=null,packages=[];for(let line of lines){let trimmed=line.trim();if(/^Automatically ignored builds during installation:/i.test(trimmed)){section2="automatic";continue}if(/^Explicitly ignored package builds/i.test(trimmed)){section2="explicit";continue}if(section2!=="automatic"||trimmed.length===0)continue;let entry=/^\s{2,}(\S.*)$/.exec(line)?.[1]?.trim();if(!entry){section2=null;continue}if(/^Cannot identify as no node_modules found$/i.test(entry))return{status:"warning",message:"Dependency lifecycle-script approval check skipped: pnpm could not identify blocked builds because node_modules was not found."};/^None$/i.test(entry)||packages.push(entry.replace(/^[-*]\s+/,""))}return packages.length>0?{status:"blocked",packageManager:"pnpm",packages:[...new Set(packages)]}:{status:"clean",packageManager:"pnpm"}}__name(parsePnpmIgnoredBuilds,"parsePnpmIgnoredBuilds");function parseBunUntrusted(output){let packages=output.split(/\r?\n/).map(line=>line.trim().replace(/^[-*]\s+/,"")).map(line=>/^\.\/node_modules\/(.+?)\s+@[^\s]+$/.exec(line)?.[1]??null).filter(packageName=>packageName!==null);return packages.length>0?{status:"blocked",packageManager:"bun",packages:[...new Set(packages)]}:{status:"clean",packageManager:"bun"}}__name(parseBunUntrusted,"parseBunUntrusted");function selectPackageManager(cwd){let packageJson=readPackageJson3(path26.join(cwd,"package.json")),exact=typeof packageJson?.packageManager=="string"?parseExactPackageManager(packageJson.packageManager):null;if(exact)return exact;let lockfiles=Object.entries(LOCKFILE_MANAGERS2).filter(([lockfile])=>fs23.existsSync(path26.join(cwd,lockfile)));return lockfiles.length!==1?null:{name:lockfiles[0][1]}}__name(selectPackageManager,"selectPackageManager");function parseExactPackageManager(value){let match=/^(pnpm|bun|npm|yarn)@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/.exec(value.trim());return match?{name:match[1],version:match[2]}:null}__name(parseExactPackageManager,"parseExactPackageManager");function supportsPnpmIgnoredBuilds(version){let match=/^(\d+)\.(\d+)\.(\d+)/.exec(version.trim());if(!match)return!1;let major=Number(match[1]),minor=Number(match[2]);return major>10||major===10&&minor>=1}__name(supportsPnpmIgnoredBuilds,"supportsPnpmIgnoredBuilds");function matchesRequestedVersion(actual,requested){return actual.trim()===requested.split("+",1)[0]}__name(matchesRequestedVersion,"matchesRequestedVersion");async function executeCommand(command,args,cwd){let result=await execFileAsync3(command,args,{cwd,encoding:"utf8"});return{stdout:String(result.stdout),stderr:String(result.stderr)}}__name(executeCommand,"executeCommand");function readPackageJson3(filePath){try{return JSON.parse(fs23.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson3,"readPackageJson");init_project_context();init_project();init_dist();import{existsSync as existsSync8,readFileSync as readFileSync8,readdirSync as readdirSync6,statSync as statSync3}from"node:fs";import{join as join9,resolve as resolve7}from"node:path";import fs24 from"node:fs/promises";import path27 from"node:path";async function pathExists(targetPath){try{return await fs24.access(targetPath),!0}catch{return!1}}__name(pathExists,"pathExists");async function removeDataFiles(dir){let entries2=await fs24.readdir(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path27.join(dir,entry.name);entry.isDirectory()?await removeDataFiles(fullPath):entry.name.endsWith(".data")&&await fs24.rm(fullPath)}}__name(removeDataFiles,"removeDataFiles");async function exportStatic(options={}){let cwd=options.cwd??process.cwd(),clientDir=path27.resolve(cwd,"dist/client"),serverDir=path27.resolve(cwd,"dist/server");if(!await pathExists(clientDir))throw new Error("Missing dist/client output. Run `react-router build` first.");await pathExists(serverDir)&&await fs24.rm(serverDir,{recursive:!0,force:!0}),await removeDataFiles(clientDir),console.log("Static export complete.")}__name(exportStatic,"exportStatic");import{existsSync as existsSync7,readFileSync as readFileSync7,readdirSync as readdirSync5,statSync as statSync2}from"fs";import{createRequire as createRequire2}from"node:module";import{join as join8}from"path";var require3=createRequire2(import.meta.url),parseSync2;function parse7(filePath,code2){return parseSync2??=require3("oxc-parser").parseSync,parseSync2(filePath,code2)}__name(parse7,"parse");var SRC_DIR="src";function getLineAndColumn(code2,offset){let lines=code2.slice(0,offset).split(`
1226
+ Fix: keep one of them, or give them distinct paths \u2014 a locale segment does not make two routes distinct.`);continue}previous||byShape.set(shape,route)}return errors}__name(validateRouteShapeCollisions,"validateRouteShapeCollisions");function validateLocaleRouteCollisions(args){let errors=[],reservedPrefixes=new Set(args.i18n.locales.map(locale=>locale.toLowerCase()));for(let route of args.configRoutes){let first2=firstPathSegment(route.path);first2&&reservedPrefixes.has(first2.toLowerCase())&&errors.push(`Route "${route.id}" (${route.path}) uses reserved locale prefix "${first2}". Declare the locale as "/:locale/..." in ${args.configDisplayPath} and as ":locale?/..." in React Router so the default locale remains unprefixed.`)}if(!args.routesSourceUsesLegacyHelper)for(let route of args.fileRoutes){if(!route.path||route.isLayout)continue;let first2=firstPathSegment(route.path);first2&&normalizeLocaleSpelling(first2)===`:${FIMO_LOCALE_PARAM}`||(first2?.startsWith(":")||first2==="*")&&errors.push(`Route "${route.path}" is a top-level dynamic route in a multi-locale project. It can capture locale URLs like "/${args.i18n.locales[0]}". Put an explicit optional ":locale?" segment first in the React Router path, or keep this route outside the localized route boundary.`)}return errors}__name(validateLocaleRouteCollisions,"validateLocaleRouteCollisions");function sourceUsesLegacyFimoRoutes(routesFilePath){if(!fs21.existsSync(routesFilePath))return!1;let source=fs21.readFileSync(routesFilePath,"utf-8"),importedName=source.match(/import\s*\{(?<imports>[^}]*)\}\s*from\s*['"]fimo\/react-router\/routes['"]/s)?.groups?.imports?.split(",").map(specifier=>specifier.trim().match(/^fimoRoutes(?:\s+as\s+(?<alias>[A-Za-z_$][\w$]*))?$/)?.groups?.alias??(specifier.trim()==="fimoRoutes"?"fimoRoutes":null)).find(name=>!!name);return importedName?new RegExp(`\\b${importedName}\\s*\\(`).test(source):!1}__name(sourceUsesLegacyFimoRoutes,"sourceUsesLegacyFimoRoutes");function normalizeLocaleSpelling(routePath){return routePath.replace(`:${FIMO_LOCALE_PARAM}?`,`:${FIMO_LOCALE_PARAM}`)}__name(normalizeLocaleSpelling,"normalizeLocaleSpelling");function registrablePaths(route){let declared=normalizeLocaleSpelling(route.contract.path);return route.contract.localeParam?.optional?[declared,route.contract.canonicalPath]:[declared]}__name(registrablePaths,"registrablePaths");function firstPathSegment(routePath){return routePath.split("/").filter(Boolean)[0]??null}__name(firstPathSegment,"firstPathSegment");function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function normalizeFimoLocale(locale){let trimmed=locale?.trim();if(!trimmed)return null;let candidate=trimmed.replace(/_/g,"-");try{return Intl.getCanonicalLocales(candidate)[0]??null}catch{return null}}__name(normalizeFimoLocale,"normalizeFimoLocale");init_esm();import{existsSync as existsSync6,readFileSync as readFileSync6,readdirSync as readdirSync4}from"node:fs";import{basename as basename2,join as join7,resolve as resolve6}from"node:path";var SCHEMAS_REL2="src/schemas",FIELD_TYPES=new Set(FieldTypeSchema.options),RESERVED_FIELD_NAMES=new Set(RESERVED_CONTENT_FIELD_NAMES);function validateSchemas(options={}){let cwd=resolve6(options.cwd??process.cwd()),schemasDir=join7(cwd,SCHEMAS_REL2);if(!existsSync6(schemasDir))return{errors:[],schemasChecked:0};let files=readdirSync4(schemasDir).filter(f=>f.endsWith(".json")).sort(),errors=[],schemaUids=new Set;for(let fileName of files){let schema=readSchemaObject(join7(schemasDir,fileName));schema&&typeof schema.uid=="string"&&schemaUids.add(schema.uid)}for(let fileName of files){let file=join7(SCHEMAS_REL2,fileName);errors.push(...validateSchemaFile(join7(schemasDir,fileName),file,schemaUids))}return{errors,schemasChecked:files.length}}__name(validateSchemas,"validateSchemas");function readSchemaObject(absolutePath){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch{return null}return typeof schema=="object"&&schema!==null&&!Array.isArray(schema)?schema:null}__name(readSchemaObject,"readSchemaObject");function validateSchemaFile(absolutePath,file,schemaUids=new Set){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch(error){return[{rule:"schemas/parse",message:`Invalid JSON: ${error instanceof Error?error.message:String(error)}`,file}]}if(typeof schema!="object"||schema===null||Array.isArray(schema))return[{rule:"schemas/shape",message:"Schema must be a JSON object.",file}];let errors=[],{uid,name,fields,i18n,isSingleton,groups}=schema,expectedUid=basename2(file,".json");if(typeof uid!="string"||uid.length===0?errors.push({rule:"schemas/uid",message:`Missing "uid". Set it to the file name: "${expectedUid}".`,file}):uid!==expectedUid?errors.push({rule:"schemas/uid",message:`"uid" is "${uid}" but the file is ${expectedUid}.json \u2014 they must match.`,file}):CONTENT_TYPE_NAME_PATTERN.test(uid)||errors.push({rule:"schemas/type-name",message:`"uid" must use ${CONTENT_TYPE_NAME_PATTERN_DESCRIPTION}.`,file}),(typeof name!="string"||name.length===0)&&errors.push({rule:"schemas/name",message:'Missing "name" (the human-readable label).',file}),isSingleton!==void 0&&typeof isSingleton!="boolean"&&errors.push({rule:"schemas/singleton",message:'"isSingleton" must be a boolean when provided.',file}),i18n!==void 0)if(typeof i18n!="object"||i18n===null||Array.isArray(i18n))errors.push({rule:"schemas/i18n",message:'"i18n" must be an object like { "enabled": false }.',file});else{let keys=Object.keys(i18n);(keys.length!==1||keys[0]!=="enabled"||typeof i18n.enabled!="boolean")&&errors.push({rule:"schemas/i18n",message:'"i18n" only supports one boolean option: { "enabled": true | false }.',file})}let groupIds=new Set;if(groups!==void 0)if(!Array.isArray(groups))errors.push({rule:"schemas/groups",message:'"groups" must be an array.',file});else{let defaults=0;for(let[index2,group]of groups.entries()){let parsed=ContentFieldGroupSchema.safeParse(group);if(!parsed.success){errors.push({rule:"schemas/groups",message:`Group at index ${index2} is invalid: ${parsed.error.issues[0]?.message??"invalid group"}.`,file});continue}groupIds.has(parsed.data.id)&&errors.push({rule:"schemas/groups",message:`Group ID "${parsed.data.id}" is declared more than once.`,file}),groupIds.add(parsed.data.id),parsed.data.default&&(defaults+=1)}defaults>1&&errors.push({rule:"schemas/groups",message:"At most one group may be the default.",file})}if(typeof fields!="object"||fields===null||Array.isArray(fields))return errors.push({rule:"schemas/fields",message:'Missing "fields" object.',file}),errors;let parsedFields={};for(let[fieldName,definition]of Object.entries(fields)){if(!CONTENT_FIELD_NAME_PATTERN.test(fieldName)){errors.push({rule:"schemas/field-name",message:`Field "${fieldName}" must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`,file});continue}if(RESERVED_FIELD_NAMES.has(fieldName)){errors.push({rule:"schemas/reserved-field",message:`Field "${fieldName}" is reserved entry metadata \u2014 the platform manages it automatically. Remove it from the schema${fieldName==="slug"?" (set slug inside entry data on create instead)":""}.`,file});continue}if(typeof definition!="object"||definition===null||Array.isArray(definition)){errors.push({rule:"schemas/field-shape",message:`Field "${fieldName}" must be an object like { "type": "string" }.`,file});continue}let{type}=definition,memberships=Array.isArray(definition.group)?definition.group:definition.group===void 0?[]:[definition.group];new Set(memberships).size!==memberships.length&&errors.push({rule:"schemas/field-group",message:`Field "${fieldName}" lists the same group more than once.`,file});for(let membership of memberships)(typeof membership!="string"||!groupIds.has(membership))&&errors.push({rule:"schemas/field-group",message:`Field "${fieldName}" references unknown group "${String(membership)}".`,file});if((typeof type!="string"||!FIELD_TYPES.has(type))&&errors.push({rule:"schemas/field-type",message:`Field "${fieldName}" has unsupported type "${String(type)}". Allowed: ${[...FIELD_TYPES].join(", ")}.`,file}),"localized"in definition&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "localized" is not supported. Use "i18n": false to share one value across locales.`,file}),"i18n"in definition&&(typeof definition.i18n!="boolean"?errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" must be true or false.`,file}):type==="blocks"&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" is not supported on blocks fields.`,file})),type==="blocks"){let parsed2=ContentFieldDefinitionSchema.safeParse(definition);if(!parsed2.success){for(let issue of parsed2.error.issues)errors.push({rule:"schemas/structured-content-shape",message:`Field "${fieldName}"${issue.path.length>0?` at ${issue.path.join(".")}`:""}: ${issue.message}`,file});continue}parsedFields[fieldName]=parsed2.data,walkContentFields({[fieldName]:parsed2.data},({field,path:path53,structuredDepth,insideStructuredContent})=>{if(insideStructuredContent&&field.group!==void 0&&errors.push({rule:"schemas/field-group",message:`Field "${path53.join(".")}" cannot use "group" inside blocks.`,file}),field.type==="blocks"&&structuredDepth>=MAX_STRUCTURED_CONTENT_DEPTH&&errors.push({rule:"schemas/structured-content-depth",message:`Field "${path53.join(".")}" exceeds the ${MAX_STRUCTURED_CONTENT_DEPTH}-level blocks limit.`,file}),!(!insideStructuredContent||field.type!=="reference")){if(field.targets){errors.push({rule:"schemas/structured-content-reference",message:`Reference field "${path53.join(".")}" must use one fixed "target" inside blocks.`,file});return}field.target&&schemaUids.size>0&&!schemaUids.has(field.target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${path53.join(".")}" targets unknown schema "${field.target}".`,file})}});continue}let parsed=ContentFieldDefinitionSchema.safeParse(definition);if(parsed.success&&(parsedFields[fieldName]=parsed.data),type==="reference"){let{target,targets,many}=definition;if(targets!==void 0&&target!==void 0)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" declares both "target" and "targets" \u2014 a field is fixed or polymorphic, never both.`,file});else if(targets!==void 0){let targetList=Array.isArray(targets)?targets:null;if(!targetList||targetList.length===0||new Set(targetList).size!==targetList.length)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare "targets" as a non-empty array of unique content types.`,file});else for(let candidate of targetList)typeof candidate!="string"||!CONTENT_TYPE_NAME_PATTERN.test(candidate)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" has an invalid entry in "targets".`,file}):schemaUids.size>0&&!schemaUids.has(candidate)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${candidate}".`,file})}else typeof target!="string"||!CONTENT_TYPE_NAME_PATTERN.test(target)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare a valid "target" content type (or "targets" for a polymorphic field).`,file}):schemaUids.size>0&&!schemaUids.has(target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${target}".`,file});many!==void 0&&typeof many!="boolean"&&errors.push({rule:"schemas/reference-many",message:`Reference field "${fieldName}" must use a boolean "many" value.`,file})}else for(let referenceOnlyKey of["target","targets","many"])referenceOnlyKey in definition&&errors.push({rule:"schemas/reference-shape",message:`Field "${fieldName}": "${referenceOnlyKey}" is only supported on reference fields.`,file})}for(let problem of collectConditionProblems(parsedFields))errors.push({rule:"schemas/conditions",message:problem.message,file});return errors}__name(validateSchemaFile,"validateSchemaFile");init_api();init_config();init_auth_errors();init_project();import fs22 from"node:fs";import path25 from"node:path";var MIN_DB_LABELS_FIMO_VERSION="0.2.5",MIN_DB_LABELS_TEMPLATE_VERSION=4;function getDbLabelsRuntimeWarning(cwd){if(readExplicitConfigVersion(cwd)<MIN_DB_LABELS_TEMPLATE_VERSION)return null;let projectPackage=readPackageJson2(path25.join(cwd,"package.json")),fimoSpec=findFimoSpec(projectPackage);if(!fimoSpec)return buildWarning("package.json has no fimo dependency");let source=findRuntimeVersion(cwd,fimoSpec);return!source||!isVersionOlder(source.version,MIN_DB_LABELS_FIMO_VERSION)?null:buildWarning(`${source.label} is fimo@${source.version}`)}__name(getDbLabelsRuntimeWarning,"getDbLabelsRuntimeWarning");function readExplicitConfigVersion(cwd){try{let raw=JSON.parse(fs22.readFileSync(resolveProjectConfigPath(cwd),"utf8")),parsed=Number.parseInt(String(raw.version),10);return Number.isFinite(parsed)&&parsed>0?parsed:0}catch{return 0}}__name(readExplicitConfigVersion,"readExplicitConfigVersion");function buildWarning(subject){return[`CRITICAL: ${subject}, but DB-owned labels require fimo >= ${MIN_DB_LABELS_FIMO_VERSION}.`,"Labels changed with `fimo labels` or Fimo Studio may not render in this project until the app runtime is upgraded.","Run `npm install fimo@latest` (or your package manager equivalent), then run `fimo validate` again."].join(" ")}__name(buildWarning,"buildWarning");function findRuntimeVersion(cwd,fimoSpec){let installed=readPackageJson2(path25.join(cwd,"node_modules","fimo","package.json"));if(typeof installed?.version=="string")return{label:"installed node_modules/fimo",version:installed.version};let packageLockVersion=readPackageLockVersion(cwd);if(packageLockVersion)return{label:"package-lock.json",version:packageLockVersion};let exactSpecVersion=parseVersion2(fimoSpec);if(exactSpecVersion)return{label:"package.json dependency",version:exactSpecVersion.normalized};if(fimoSpec.startsWith("file:")){let fileVersion=readFileDependencyVersion(cwd,fimoSpec);if(fileVersion)return{label:"package.json file dependency target",version:fileVersion}}return null}__name(findRuntimeVersion,"findRuntimeVersion");function findFimoSpec(pkg){let dependenciesSpec=pkg?.dependencies?.fimo;if(typeof dependenciesSpec=="string"&&dependenciesSpec.trim())return dependenciesSpec.trim();let devDependenciesSpec=pkg?.devDependencies?.fimo;return typeof devDependenciesSpec=="string"&&devDependenciesSpec.trim()?devDependenciesSpec.trim():null}__name(findFimoSpec,"findFimoSpec");function readFileDependencyVersion(cwd,spec){let rawPath=spec.slice(5),packageRoot=path25.isAbsolute(rawPath)?rawPath:path25.resolve(cwd,rawPath),pkg=readPackageJson2(path25.join(packageRoot,"package.json"));return typeof pkg?.version=="string"?pkg.version:null}__name(readFileDependencyVersion,"readFileDependencyVersion");function readPackageLockVersion(cwd){try{let lock=JSON.parse(fs22.readFileSync(path25.join(cwd,"package-lock.json"),"utf8")),packagesVersion=lock.packages?.["node_modules/fimo"]?.version;if(typeof packagesVersion=="string")return packagesVersion;let dependencyVersion=lock.dependencies?.fimo?.version;return typeof dependencyVersion=="string"?dependencyVersion:null}catch{return null}}__name(readPackageLockVersion,"readPackageLockVersion");function readPackageJson2(filePath){try{return JSON.parse(fs22.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson2,"readPackageJson");function isVersionOlder(version,minimum){let parsed=parseVersion2(version),parsedMinimum=parseVersion2(minimum);if(!parsed||!parsedMinimum)return!1;for(let key of["major","minor","patch"]){if(parsed[key]<parsedMinimum[key])return!0;if(parsed[key]>parsedMinimum[key])return!1}return!1}__name(isVersionOlder,"isVersionOlder");function parseVersion2(version){let match=version.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return match?{major:Number(match[1]),minor:Number(match[2]),patch:Number(match[3]),normalized:`${Number(match[1])}.${Number(match[2])}.${Number(match[3])}`}:null}__name(parseVersion2,"parseVersion");import{execFile as execFile3}from"node:child_process";import fs23 from"node:fs";import path26 from"node:path";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3),LOCKFILE_MANAGERS2={"pnpm-lock.yaml":"pnpm","bun.lock":"bun","bun.lockb":"bun","yarn.lock":"yarn","package-lock.json":"npm"};async function inspectDependencyLifecycleScripts(cwd,execute=executeCommand){let selection=selectPackageManager(cwd);if(!selection)return{status:"warning",message:"Dependency lifecycle-script approval check skipped: no package manager could be selected from package.json or a lockfile."};if(!fs23.existsSync(path26.join(cwd,"node_modules")))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: ${selection.name} has no installed node_modules state to inspect.`};if(selection.name==="yarn")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: Yarn has no stable standalone blocked-script listing command."};if(selection.name==="npm")return{status:"warning",message:"Dependency lifecycle-script approval check skipped: this npm version has no supported read-only blocked-script listing command."};try{let versionResult=await execute(selection.name,["--version"],cwd);if(selection.version&&!matchesRequestedVersion(versionResult.stdout,selection.version))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: the installed ${selection.name} version ${versionResult.stdout.trim()||"unknown"} does not match the exact packageManager pin ${selection.name}@${selection.version}.`};if(selection.name==="pnpm"&&!supportsPnpmIgnoredBuilds(versionResult.stdout))return{status:"warning",message:`Dependency lifecycle-script approval check skipped: pnpm ${versionResult.stdout.trim()||"unknown"} does not support pnpm ignored-builds inspection (requires pnpm 10.1+).`};let args=selection.name==="pnpm"?["ignored-builds"]:["pm","untrusted"],result=await execute(selection.name,args,cwd);return selection.name==="pnpm"?parsePnpmIgnoredBuilds(result.stdout,fs23.existsSync(path26.join(cwd,"node_modules",".modules.yaml"))):parseBunUntrusted(result.stdout)}catch(error){return{status:"warning",message:`Dependency lifecycle-script approval check skipped: could not inspect ${selection.name} install state (${error instanceof Error?error.message:String(error)}).`}}}__name(inspectDependencyLifecycleScripts,"inspectDependencyLifecycleScripts");function parsePnpmIgnoredBuilds(output,hasModulesManifest){let lines=output.split(/\r?\n/),section2=null,sawAutomaticSection=!1,sawExplicitSection=!1,sawNone=!1,packages=[];for(let line of lines){let trimmed=line.trim();if(/^Automatically ignored builds during installation:/i.test(trimmed)){section2="automatic",sawAutomaticSection=!0;continue}if(/^Explicitly ignored package builds/i.test(trimmed)){section2="explicit",sawExplicitSection=!0;continue}if(section2!=="automatic"||trimmed.length===0)continue;let entry=/^\s{2,}(\S.*)$/.exec(line)?.[1]?.trim();if(!entry){section2=null;continue}if(/^Cannot identify as no node_modules found$/i.test(entry))return{status:"warning",message:hasModulesManifest?"Dependency lifecycle-script approval check skipped: pnpm could not confirm whether dependency install scripts were blocked.":"Dependency lifecycle-script approval check skipped: pnpm recorded no install state under node_modules to inspect."};if(/^None$/i.test(entry))sawNone=!0;else{let packageEntry=entry.replace(/^[-*]\s+/,"");if(/\s/.test(packageEntry))return unrecognizedOutput("pnpm");packages.push(pnpmPackageName(packageEntry))}}return packages.length>0?{status:"blocked",packageManager:"pnpm",packages:[...new Set(packages)]}:sawAutomaticSection&&(sawExplicitSection||sawNone)?{status:"clean",packageManager:"pnpm"}:unrecognizedOutput("pnpm")}__name(parsePnpmIgnoredBuilds,"parsePnpmIgnoredBuilds");function parseBunUntrusted(output){let packages=output.split(/\r?\n/).map(line=>line.trim().replace(/^[-*]\s+/,"")).map(line=>/^\.\/node_modules\/(.+?)\s+@[^\s]+$/.exec(line)?.[1]??null).filter(packageName=>packageName!==null);return packages.length>0&&/These dependencies had their lifecycle scripts blocked during install\./i.test(output)?{status:"blocked",packageManager:"bun",packages:[...new Set(packages)]}:/Found 0 untrusted dependencies with scripts\./i.test(output)?{status:"clean",packageManager:"bun"}:unrecognizedOutput("bun")}__name(parseBunUntrusted,"parseBunUntrusted");function unrecognizedOutput(packageManager){return{status:"warning",message:`Dependency lifecycle-script approval check skipped: ${packageManager} returned unrecognized successful output.`}}__name(unrecognizedOutput,"unrecognizedOutput");function pnpmPackageName(entry){return(entry.startsWith("@")?/^(@[^/]+\/[^@]+)(?:@.+)?$/.exec(entry):/^([^@]+)(?:@.+)?$/.exec(entry))?.[1]??entry}__name(pnpmPackageName,"pnpmPackageName");function selectPackageManager(cwd){let packageJson=readPackageJson3(path26.join(cwd,"package.json")),exact=typeof packageJson?.packageManager=="string"?parseExactPackageManager(packageJson.packageManager):null;if(exact)return exact;let lockfiles=Object.entries(LOCKFILE_MANAGERS2).filter(([lockfile])=>fs23.existsSync(path26.join(cwd,lockfile)));return lockfiles.length!==1?null:{name:lockfiles[0][1]}}__name(selectPackageManager,"selectPackageManager");function parseExactPackageManager(value){let match=/^(pnpm|bun|npm|yarn)@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/.exec(value.trim());return match?{name:match[1],version:match[2]}:null}__name(parseExactPackageManager,"parseExactPackageManager");function supportsPnpmIgnoredBuilds(version){let match=/^(\d+)\.(\d+)\.(\d+)/.exec(version.trim());if(!match)return!1;let major=Number(match[1]),minor=Number(match[2]);return major>10||major===10&&minor>=1}__name(supportsPnpmIgnoredBuilds,"supportsPnpmIgnoredBuilds");function matchesRequestedVersion(actual,requested){return actual.trim()===requested.split("+",1)[0]}__name(matchesRequestedVersion,"matchesRequestedVersion");async function executeCommand(command,args,cwd){let result=await execFileAsync3(command,args,{cwd,encoding:"utf8"});return{stdout:String(result.stdout),stderr:String(result.stderr)}}__name(executeCommand,"executeCommand");function readPackageJson3(filePath){try{return JSON.parse(fs23.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson3,"readPackageJson");init_project_context();init_project();init_dist();import{existsSync as existsSync8,readFileSync as readFileSync8,readdirSync as readdirSync6,statSync as statSync3}from"node:fs";import{join as join9,resolve as resolve7}from"node:path";import fs24 from"node:fs/promises";import path27 from"node:path";async function pathExists(targetPath){try{return await fs24.access(targetPath),!0}catch{return!1}}__name(pathExists,"pathExists");async function removeDataFiles(dir){let entries2=await fs24.readdir(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path27.join(dir,entry.name);entry.isDirectory()?await removeDataFiles(fullPath):entry.name.endsWith(".data")&&await fs24.rm(fullPath)}}__name(removeDataFiles,"removeDataFiles");async function exportStatic(options={}){let cwd=options.cwd??process.cwd(),clientDir=path27.resolve(cwd,"dist/client"),serverDir=path27.resolve(cwd,"dist/server");if(!await pathExists(clientDir))throw new Error("Missing dist/client output. Run `react-router build` first.");await pathExists(serverDir)&&await fs24.rm(serverDir,{recursive:!0,force:!0}),await removeDataFiles(clientDir),console.log("Static export complete.")}__name(exportStatic,"exportStatic");import{existsSync as existsSync7,readFileSync as readFileSync7,readdirSync as readdirSync5,statSync as statSync2}from"fs";import{createRequire as createRequire2}from"node:module";import{join as join8}from"path";var require3=createRequire2(import.meta.url),parseSync2;function parse7(filePath,code2){return parseSync2??=require3("oxc-parser").parseSync,parseSync2(filePath,code2)}__name(parse7,"parse");var SRC_DIR="src";function getLineAndColumn(code2,offset){let lines=code2.slice(0,offset).split(`
1226
1227
  `);return{line:lines.length,column:lines[lines.length-1].length+1}}__name(getLineAndColumn,"getLineAndColumn");function isStringLiteral(node){return node?node.type==="Literal"&&typeof node.value=="string"||node.type==="TemplateLiteral"&&(!node.expressions||node.expressions.length===0):!1}__name(isStringLiteral,"isStringLiteral");var DYNAMIC_KEY_MESSAGE=`Dynamic translation key detected. The first argument to t() must be a string literal, not a variable or expression.
1227
1228
 
1228
1229
  This breaks source tracking for inline editing. Translation keys must be statically analyzable.
@@ -1469,7 +1470,7 @@ Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=lite
1469
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",`
1470
1471
  Logs come from the sandbox's own process buffers, so they end when the sandbox does.
1471
1472
  There is no --follow; re-run the command instead.
1472
- `).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("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
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=`
1473
1474
  Supported agents:
1474
1475
  Universal (always covered via AGENTS.md, no per-agent file needed):
1475
1476
  Codex, OpenCode, Aider, and other AGENTS.md-native tools