fimo 0.9.0-experimental.1 → 0.9.0-experimental.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -433,7 +433,7 @@ ${end2.comment}`:end2.comment}this.doc.range[2]=end2.offset;break}default:this.e
433
433
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
434
434
  `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent2){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser3}});var require_public_api2=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),errors2=require_errors2(),log=require_log2(),identity2=require_identity2(),lineCounter=require_line_counter2(),parser=require_parser3();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors2.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors2.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument2(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors2.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors2.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors2.prettifyError(source,lineCounter2))),doc}__name(parseDocument2,"parseDocument");function parse14(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument2(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse14,"parse");function stringify4(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document2.Document(value,_replacer,options).toString(options)}__name(stringify4,"stringify");exports2.parse=parse14;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument2;exports2.stringify=stringify4}});var require_dist2=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),Schema=require_Schema2(),errors2=require_errors2(),Alias=require_Alias2(),identity2=require_identity2(),Pair=require_Pair2(),Scalar=require_Scalar2(),YAMLMap=require_YAMLMap2(),YAMLSeq=require_YAMLSeq2(),cst=require_cst2(),lexer=require_lexer2(),lineCounter=require_line_counter2(),parser=require_parser3(),publicApi=require_public_api2(),visit2=require_visit2();exports2.Composer=composer.Composer;exports2.Document=Document2.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors2.YAMLError;exports2.YAMLParseError=errors2.YAMLParseError;exports2.YAMLWarning=errors2.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import fs10 from"node:fs";import path11 from"node:path";function loadProjectSettings(cwd){let settingsPath=path11.join(cwd,".fimo.settings.json");if(!fs10.existsSync(settingsPath))throw new Error("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project.");return JSON.parse(fs10.readFileSync(settingsPath,"utf-8"))}function findProjectRoot(start){let dir=path11.resolve(start);for(;;){if(fs10.existsSync(path11.join(dir,".fimo.settings.json")))return dir;let parent2=path11.dirname(dir);if(parent2===dir)return null;dir=parent2}}function resolveProjectCwd(cwdOption){let start=path11.resolve(cwdOption??process.cwd());return findProjectRoot(start)??start}var init_project=__esm({"src/cli/utils/project.ts"(){__name(loadProjectSettings,"loadProjectSettings");__name(findProjectRoot,"findProjectRoot");__name(resolveProjectCwd,"resolveProjectCwd")}});function colorEnabled(opts={}){if(opts.forceDisable)return!1;let env=opts.env??process.env;return env.NO_COLOR&&env.NO_COLOR.length>0?!1:env.FORCE_COLOR&&env.FORCE_COLOR!=="0"&&env.FORCE_COLOR!=="false"?!0:(opts.isTTY??process.stdout.isTTY??!1)===!0}function makeColorPalette(opts={}){let on=colorEnabled(opts),wrap2=__name(style=>s=>on?`${ANSI[style]}${s}${ANSI.reset}`:s,"wrap");return{enabled:on,bold:wrap2("bold"),dim:wrap2("dim"),red:wrap2("red"),green:wrap2("green"),yellow:wrap2("yellow"),blue:wrap2("blue"),magenta:wrap2("magenta"),cyan:wrap2("cyan"),gray:wrap2("gray")}}var ANSI,palette,init_color=__esm({"src/cli/utils/format/color.ts"(){ANSI={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};__name(colorEnabled,"colorEnabled");__name(makeColorPalette,"makeColorPalette");palette=makeColorPalette()}});function isCliAuthError(err){return err instanceof NotAuthenticatedError||err instanceof UnauthorizedError||err instanceof PermissionDeniedError}function rethrowCliAuthError(err,beforeThrow){if(isCliAuthError(err))throw beforeThrow?.(err),err}function retryCommand(args=process.argv.slice(2)){return["fimo",...args].map(formatShellArg).join(" ")}function formatCliAuthError(err,opts={}){let p2=opts.palette??palette,command=retryCommand(opts.args);if(err instanceof PermissionDeniedError)return[`${p2.red("\u2717")} You don't have permission to run this command.`,"",err.required.length?` Missing permission: ${p2.bold(err.required.join(", "))}`:" Your role on this project does not allow this action."," Ask a project admin for access, or use an account with a higher role.","",p2.dim(` Backend: ${err.apiUrl}`)].join(`
435
435
  `);let expired=err instanceof UnauthorizedError,intro=expired?"Your Fimo session is expired or invalid.":"You're not signed in to Fimo.",loginVerb=expired?"refresh your session":"sign in";return[`${p2.red("\u2717")} ${intro}`,"",` Run this to ${loginVerb}:`,` ${p2.bold("fimo login")}`,""," Then retry:",` ${p2.bold(command)}`,"",p2.dim(` Backend: ${err.apiUrl}`)].join(`
436
- `)}function renderCliAuthError(err,opts={}){console.error(formatCliAuthError(err,opts))}function formatShellArg(arg){return/^[A-Za-z0-9_/:=.,@%+-]+$/.test(arg)?arg:`'${arg.replace(/'/g,"'\\''")}'`}var init_auth_errors=__esm({"src/cli/utils/auth-errors.ts"(){init_api();init_auth();init_color();__name(isCliAuthError,"isCliAuthError");__name(rethrowCliAuthError,"rethrowCliAuthError");__name(retryCommand,"retryCommand");__name(formatCliAuthError,"formatCliAuthError");__name(renderCliAuthError,"renderCliAuthError");__name(formatShellArg,"formatShellArg")}});import{z as z7}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z7.ZodOptional||schema instanceof z7.ZodNullable||schema instanceof z7.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z7.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z7.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 z7.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z7.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],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z7.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 z7.ZodObject)return createObjectDTO(schema);if(schema instanceof z7.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 z8}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z8.object({data:dataSchema}),"createResponseSchema")}});import{z as z9}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z9.object({page:z9.coerce.number().int().positive().default(1),limit:z9.coerce.number().int().positive().max(100).default(20)})}});import{z as z10}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,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:z10.coerce.date(),positiveInt:z10.number().int().positive(),nonNegativeInt:z10.number().int().nonnegative()},BaseEntitySchema=z10.object({id:z10.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z10.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z10.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z10.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z10.enum(["public","private"]),ProjectStatusSchema=z10.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z10.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z10.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z10.enum(["owner","admin","member"]),AssetTypeSchema=z10.enum(["file","folder"]),TemplateCodeSchema=z10.enum(["Free","Premium"]),FieldTypeSchema=z10.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],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_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]))}});import{z as z11}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z11.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z12}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 ReferenceValueSchema,PolymorphicReferenceValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");ReferenceValueSchema=z12.preprocess(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({documentId:z12.uuid()}));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");PolymorphicReferenceValueSchema=z12.preprocess(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({contentType:z12.string().min(1),documentId:z12.uuid()}))}});import{z as z13}from"zod";function rejectFieldLocaleSettings(field,ctx){for(let key of["i18n","localized"])key in field&&ctx.addIssue({code:"custom",path:[key],message:"Field-level locale settings are not supported."})}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk2=__name((currentFields,path64,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path64,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)walk2(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk2(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk2(fields,[],0,!1)}var MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,commonFieldShape,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();MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],commonFieldShape={label:z13.string().min(1).optional(),description:z13.string().optional(),editable:z13.boolean().optional(),required:z13.boolean().optional(),default:z13.unknown().optional()};__name(rejectFieldLocaleSettings,"rejectFieldLocaleSettings");scalarFieldSchema=z13.object({...commonFieldShape,type:z13.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z13.number().optional(),max:z13.number().optional(),minLength:z13.number().int().nonnegative().optional(),maxLength:z13.number().int().nonnegative().optional(),regex:z13.string().optional(),multiple:z13.boolean().optional(),allowedMimeTypes:z13.array(z13.string()).optional()}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(field,ctx);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.`})}),referenceFieldSchema=z13.object({...commonFieldShape,type:z13.literal("reference"),target:z13.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z13.array(z13.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z13.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(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"])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=z13.lazy(()=>contentFieldDefinitionSchema),blockFieldsSchema=z13.record(z13.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.`})}),blockVariantSchema=z13.object({uid:z13.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z13.string().min(1),description:z13.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z13.object({fields:blockFieldsSchema}).strict(),blocksSchema=z13.object({oneOf:z13.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=z13.object({...commonFieldShape,type:z13.literal("blocks"),min:z13.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z13.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z13.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(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"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z13.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z14}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","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z14.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z14.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z14.enum(AUDIT_ACTOR_KINDS)}});import{z as z15}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,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z15.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z15.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","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:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z15.object({permissions:z15.array(OpsPermissionSchema).min(1),backendProfiles:z15.array(OpsBackendProfileSchema).min(1),enabled:z15.boolean().default(!0)}),OpsServiceTokenInputSchema=z15.object({name:z15.string().trim().min(1).max(120),permissions:z15.array(OpsPermissionSchema).min(1),backendProfiles:z15.array(OpsBackendProfileSchema).min(1),expiresAt:z15.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=z15.object({importanceReason:z15.string().trim().min(1).max(1e3),ownerUserId:z15.string().trim().min(1).nullable().optional(),framework:z15.string().trim().max(120).nullable().optional(),packageManager:z15.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z15.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z15.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z15.object({projectId:z15.uuid(),title:z15.string().trim().min(1).max(240),userReport:z15.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z15.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z15.string().trim().max(1e4).nullable().optional(),outcome:z15.string().trim().max(1e4).nullable().optional(),evidence:z15.array(z15.record(z15.string(),z15.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=z15.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z15.object({fingerprint:z15.string().trim().min(1).max(240),title:z15.string().trim().min(1).max(240),description:z15.string().trim().min(1).max(1e4),affectedVersions:z15.array(z15.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z15.array(z15.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z15.string().trim().min(1).max(64).nullable().optional(),workaround:z15.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z15.array(z15.string().trim().min(1).max(120)).max(100),detectionQueries:z15.array(z15.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=z15.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z15.object({changeReference:z15.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z15.string().trim().min(1).max(1e4),evidence:z15.array(z15.record(z15.string(),z15.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z15.object({recipientEmail:z15.email().optional(),subject:z15.string().trim().min(1).max(200).default("An update from Fimo"),message:z15.string().trim().min(1).max(5e3),locale:z15.string().trim().min(2).max(20),reason:z15.string().trim().min(1).max(1e3),acknowledgePolicy:z15.literal(!0)})}});import{z as z16}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionListResponseSchema,ProjectVersionResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z16.string(),displayName:z16.string().nullable(),subdomain:z16.string().nullable().optional(),subdomainUpdatedAt:z16.date().nullable().optional(),organizationId:z16.string().nullable(),createdBy:z16.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z16.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z16.string(),thumbnailUrl:z16.string().nullable(),publishedThumbnailUrl:z16.string().nullable(),category:z16.string().nullable(),appUrl:z16.string().nullable(),lastPublishedAt:z16.coerce.date(),styleEditing:z16.boolean().optional()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z16.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z16.object({id:z16.uuid(),name:z16.string(),displayName:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),visibility:ProjectVisibilitySchema,category:z16.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z16.object({id:z16.string(),name:z16.string(),avatar:z16.string().nullable(),color:z16.object({bg:z16.string(),text:z16.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z16.object({path:z16.string(),content:z16.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z16.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z16.object({id:z16.string(),messageId:z16.string(),versionId:z16.string().nullable(),role:ProjectChatMessageRole,parts:z16.array(z16.any()),createdAt:z16.coerce.date()}),MessageUserMetadataSchema=z16.object({id:z16.string(),name:z16.string().nullable().optional(),image:z16.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z16.object({shortTitle:z16.string().optional(),questions:z16.array(z16.object({header:z16.string(),question:z16.string(),answer:z16.string(),selectedLabels:z16.array(z16.string()),freeText:z16.string(),skipped:z16.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z16.number(),metadata:z16.object({user:MessageUserMetadataSchema,changeManifest:z16.array(z16.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z16.object({id:z16.uuid(),versionId:z16.string(),projectId:z16.uuid(),commitHash:z16.string(),name:z16.string(),description:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z16.object({content:z16.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z16.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z16.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z16.object({success:z16.boolean(),message:z16.string().optional()})),ProjectPublicationStateDTOSchema=z16.object({isPublished:z16.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z16.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z16.object({success:z16.boolean(),message:z16.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z17}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z17.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z17.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z17.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z17.string().nullable(),deletedAt:z17.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z17.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z17.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z17.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z17.object({surface:z17.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z17.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z17.number().int().nonnegative(),conflictCount:z17.number().int().nonnegative()}),EnvDiffResultSchema=z17.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z17.coerce.date(),surfaces:z17.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z18}from"zod";var 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=z18.object({success:z18.literal(!0),downloadUrl:z18.string(),expiresAt:z18.string(),fileSize:z18.number(),duration:z18.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z18.object({success:z18.literal(!0),projectId:z18.string(),projectName:z18.string(),displayName:z18.string(),projectUrl:z18.string(),duration:z18.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z18.object({contentTypes:z18.number(),entries:z18.number(),assets:z18.number(),translations:z18.number(),forms:z18.number(),codeFiles:z18.number(),assetFiles:z18.number()}),ImportPreviewSurfaceDTOSchema=z18.object({name:z18.string(),included:z18.boolean(),count:z18.number().optional(),note:z18.string().optional()}),ImportPreviewDTOSchema=z18.object({projectName:z18.string(),displayName:z18.string().nullable(),visibility:z18.string().nullable(),category:z18.string().nullable(),exportedAt:z18.string(),version:z18.string(),envScope:z18.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z18.array(ImportPreviewSurfaceDTOSchema),fileSize:z18.number(),fileName:z18.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z18.object({success:z18.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z19}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z19.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z19.object({type:z19.literal("manual")}),ScheduleTriggerSchema=z19.object({type:z19.literal("schedule"),cron:z19.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:z19.string().optional()}),WebhookTriggerSchema2=z19.object({type:z19.literal("webhook"),path:z19.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z19.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z20}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z20.object({triggerIndices:z20.array(z20.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z20.object({triggerIndices:z20.array(z20.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z20.object({projectId:z20.uuid(),env:EnvSchema,agentName:z20.string().min(1),triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z20.boolean(),lastFiredAt:z20.coerce.date().nullable(),webhookPath:z20.string().nullable(),createdAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z20.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z20.object({error:z20.literal("webhook_path_taken"),conflictAgent:z20.string(),path:z20.string()}),ManualRunRequestSchema=z20.object({args:z20.unknown().optional(),requestId:z20.string().min(1).max(128).optional()}),DispatchSkippedSchema=z20.object({skipped:z20.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z20.object({sessionId:z20.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z20.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z21}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=z21.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z21.object({token:z21.string().min(1),risk:CapabilityRiskTierSchema,description:z21.string()}),AgentSubAgentSummarySchema=z21.object({name:z21.string().min(1),grant:z21.enum(["inherit","explicit"]),effectiveCaps:z21.array(z21.string().min(1))}),AgentInstallSummaryDTOSchema=z21.object({agentName:z21.string().min(1),env:z21.string().min(1),declaredCapabilities:z21.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z21.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z21.array(CapabilitySummaryEntrySchema),criticalCapabilities:z21.array(CapabilitySummaryEntrySchema),subAgents:z21.array(AgentSubAgentSummarySchema),declaresDelegate:z21.boolean(),cycle:z21.array(z21.string()).nullable(),missingSubAgents:z21.array(z21.string()),warnings:z21.array(z21.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z22}from"zod";var AgentListItemTriggerSchema,AgentListItemActivationSchema,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=z22.object({kind:TriggerKindSchema,summary:z22.string()}),AgentListItemActivationSchema=z22.object({triggerIndex:z22.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z22.string().min(1),active:z22.boolean()}),AgentListItemDTOSchema=z22.object({name:z22.string().min(1),description:z22.string().nullable(),goalFirstLine:z22.string().nullable(),declaredCapabilities:z22.array(CapabilitySummaryEntrySchema),triggers:z22.array(AgentListItemTriggerSchema),activations:z22.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z22.array(AgentListItemDTOSchema))}});import{z as z23}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z23.object({cpuMs:z23.number().nonnegative().default(0),netBytes:z23.number().nonnegative().default(0),walltimeMs:z23.number().nonnegative().default(0),llmTokensIn:z23.number().nonnegative().optional(),llmTokensOut:z23.number().nonnegative().optional()}),AgentSessionDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),env:EnvSchema,agentName:z23.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z23.unknown().optional(),capabilities:z23.array(z23.string()).optional(),dataSources:z23.array(z23.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z23.string().nullable(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),cancelledAt:z23.coerce.date().nullable(),costUsd:z23.number().nonnegative(),costCeilingUsd:z23.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z23.boolean(),lastCheckpointId:z23.uuid().nullable(),branchEnvId:z23.uuid().nullable(),parentSessionId:z23.uuid().nullable(),terminalReason:z23.string().nullable(),errorMessage:z23.string().nullable(),report:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z23.object({id:z23.uuid(),sessionId:z23.uuid(),checkpointIdx:z23.number().int().nonnegative(),payloadRef:z23.string(),payloadSizeBytes:z23.number().int().nonnegative(),checksum:z23.string().length(64),createdAt:z23.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z23.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z23.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z23.object({session:AgentSessionDTOSchema,checkpoints:z23.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z23.object({reason:z23.string().min(1).max(120).optional()})}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z25.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z25.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z25.enum(["secret_text"]),IntegrationCredentialUsageSchema=z25.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z25.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z25.object({mode:IntegrationAuthModeSchema,label:z25.string().min(1),description:z25.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z25.object({id:z25.string().min(1),label:z25.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z25.boolean()}),IntegrationToolDefinitionDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),description:z25.string().min(1)}),IntegrationRecipeDTOSchema=z25.object({title:z25.string().min(1),description:z25.string().min(1),command:z25.string().min(1).optional()}),IntegrationInfoDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z25.array(IntegrationAuthModeDTOSchema),credentials:z25.array(IntegrationCredentialDefinitionDTOSchema),tools:z25.array(IntegrationToolDefinitionDTOSchema),recipes:z25.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),installed:z25.boolean(),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z25.string().nullable(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),installedAt:z25.coerce.date().nullable(),updatedAt:z25.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z25.string(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z25.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z25.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z25.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z25.object({value:z25.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z25.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z25.object({id:z25.uuid(),organizationId:z25.string().min(1),integrationKey:z25.string().min(1),alias:z25.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z25.string().min(1),externalAccountName:z25.string().nullable(),externalBotUserId:z25.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z25.array(z25.string()),connectedAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z25.object({alias:z25.string().min(1).max(120).optional(),token:z25.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z25.object({integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z25.object({ref:z25.string().min(1),connectionAlias:z25.string().min(1).optional(),agentName:z25.string().min(1).max(160).nullable().optional(),force:z25.boolean().optional()}),ProjectChannelBindingDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),connectionId:z25.uuid(),externalWorkspaceId:z25.string().min(1),externalChannelId:z25.string().min(1),externalChannelName:z25.string().nullable(),agentName:z25.string().nullable(),enabled:z25.boolean(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z25.object({markdown:z25.boolean().optional(),summary:z25.boolean().optional(),links:z25.boolean().optional(),images:z25.boolean().optional(),html:z25.union([z25.literal("cleaned"),z25.literal("raw"),z25.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z25.object({url:z25.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z25.object({query:z25.string().min(1),maxResults:z25.number().int().positive().max(20).optional(),sources:z25.array(z25.enum(["web","news","images"])).min(1).max(3).optional(),categories:z25.array(z25.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z25.enum(["hour","day","week","month","year"]).optional(),location:z25.string().min(1).max(160).optional(),country:z25.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z25.object({url:z25.string().url(),search:z25.string().min(1).optional(),limit:z25.number().int().positive().max(200).optional(),includeSubdomains:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z25.object({url:z25.string().url(),limit:z25.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z25.object({text:z25.string().min(1).max(200).optional(),cron:z25.string().min(1).max(120).optional(),timezone:z25.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z25.object({type:z25.enum(["scrape","crawl"]).default("scrape"),urls:z25.array(z25.string().url()).min(1).max(50),scrapeOptions:z25.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z25.object({name:z25.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z25.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z25.string().min(1).max(2e3).optional(),judgeEnabled:z25.boolean().optional(),retentionDays:z25.number().int().min(1).max(365).optional(),notification:z25.object({email:z25.object({enabled:z25.boolean().default(!0),recipients:z25.array(z25.string().email()).min(1).max(20),includeDiffs:z25.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z25.object({monitorId:z25.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z25.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z25.object({connectionAlias:z25.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z25.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.list"),input:z25.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z25.object({provider:z25.string().min(1),providerCredits:z25.number().nonnegative().optional(),providerCostUsd:z25.number().nonnegative().optional(),requests:z25.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z25.object({credits:z25.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()}),FirecrawlSearchToolOutputSchema=z25.object({query:z25.string(),provider:z25.literal("firecrawl"),warning:z25.string().optional(),results:z25.array(z25.object({title:z25.string(),url:z25.string(),snippet:z25.string().optional(),content:z25.string().optional(),score:z25.number().optional(),publishedAt:z25.string().optional()}))}),FirecrawlMapToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),count:z25.number(),links:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),description:z25.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),total:z25.number(),pages:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()})),warning:z25.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z25.object({cron:z25.string().optional(),text:z25.string().optional(),timezone:z25.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z25.object({id:z25.string().optional(),urls:z25.array(z25.string()).optional(),scrapeOptions:z25.record(z25.string(),z25.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z25.object({id:z25.string(),name:z25.string(),status:z25.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z25.string().nullable().optional(),lastRunAt:z25.string().nullable().optional(),currentCheckId:z25.string().nullable().optional(),targets:z25.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z25.string().nullable().optional(),judgeEnabled:z25.boolean().optional(),estimatedCreditsPerMonth:z25.number().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z25.object({id:z25.string(),monitorId:z25.string(),scheduledFor:z25.string().nullable().optional(),startedAt:z25.string().nullable().optional(),finishedAt:z25.string().nullable().optional(),estimatedCredits:z25.number().optional(),reservedCredits:z25.number().optional(),actualCredits:z25.number().optional(),billingStatus:z25.string().nullable().optional(),summary:z25.object({totalPages:z25.number().optional(),same:z25.number().optional(),changed:z25.number().optional(),new:z25.number().optional(),removed:z25.number().optional(),error:z25.number().optional()}).passthrough().optional(),error:z25.string().nullable().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitors:z25.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),deleted:z25.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),checks:z25.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),check:FirecrawlMonitorCheckOutputSchema,next:z25.string().optional()}),FirecrawlToolKeySchema=z25.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z25.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z25.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z25.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z25.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z25.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z26}from"zod";var ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,ProjectScheduleResponseSchema,ProjectSchedulesListResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_create_dto();init_response();ProjectScheduleStatusSchema=z26.enum(["ok","failed"]),ProjectScheduleDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),env:z26.string().min(1),name:z26.string().min(1),cron:z26.string().min(1),command:z26.string().min(1),enabled:z26.boolean(),lastRunAt:z26.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z26.object({name:z26.string().min(1).max(120),cron:z26.string().min(1).max(120),command:z26.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z26.array(ProjectScheduleDTOSchema))}});import{z as z27}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z27.object({id:z27.uuid(),occurredAt:z27.coerce.date(),projectId:z27.uuid().nullable(),env:z27.string().nullable(),actor:z27.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z27.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z27.unknown().optional(),ipAddress:z27.string().nullable().optional(),userAgent:z27.string().nullable().optional(),error:z27.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z27.object({rows:z27.array(AuditLogRowDTOSchema),nextCursor:z27.string().nullable()})),AuditLogQuerySchema=z27.object({env:z27.string().optional(),action:AuditActionSchema.optional(),actor:z27.string().optional(),from:z27.coerce.date().optional(),to:z27.coerce.date().optional(),limit:z27.coerce.number().int().min(1).max(200).optional(),cursor:z27.string().optional()})}});import{z as z28}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,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,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=z28.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z28.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z28.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z28.object({verb:SurfaceDeltaVerbSchema,key:z28.string(),detail:z28.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z28.record(z28.string(),z28.unknown()).optional()}),PerSurfaceDeltaSchema=z28.object({surface:SurfaceNameSchema,status:z28.enum(["ok","timed_out","failed","unchanged"]),durationMs:z28.number().int().nonnegative().optional(),changedCount:z28.number().int().nonnegative(),conflictCount:z28.number().int().nonnegative(),items:z28.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z28.boolean().optional(),error:z28.string().optional()}),CrossSurfaceFindingSchema=z28.object({id:z28.string(),kind:z28.string(),description:z28.string(),severity:z28.enum(["warning","error"]),source:z28.object({surface:SurfaceNameSchema,key:z28.string()}),target:z28.object({surface:SurfaceNameSchema,key:z28.string()}),actions:z28.array(z28.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z28.object({env:EnvSchema,vs:EnvSchema,syncState:z28.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z28.coerce.date(),surfaces:z28.array(PerSurfaceDeltaSchema),agents:z28.array(z28.object({id:z28.string(),name:z28.string(),status:z28.enum(["active","paused","failed"]),lastRunAt:z28.coerce.date().nullable()})).optional(),crossSurface:z28.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z28.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z28.coerce.date(),surfaces:z28.array(PerSurfaceDeltaSchema),crossSurface:z28.array(CrossSurfaceFindingSchema).optional(),fingerprint:z28.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z28.object({path:z28.string(),state:z28.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z28.string(),additions:z28.number().int().nonnegative(),deletions:z28.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z28.object({oid:z28.string().optional(),content:z28.string().optional(),truncated:z28.boolean(),binary:z28.boolean()}),CodeConflictDetailSchema=z28.object({path:z28.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z28.string(),targetTipSha:z28.string(),mergeBaseSha:z28.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z28.object({id:z28.string(),slug:z28.string(),contentType:z28.string(),data:z28.record(z28.string(),z28.unknown()),updatedAt:z28.coerce.date()}),ContentRowDiffSchema=z28.object({collection:z28.string(),rowId:z28.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z28.object({name:z28.string(),label:z28.string(),isSingleton:z28.boolean(),fields:z28.record(z28.string(),z28.unknown())}),SchemaTypeDiffSchema=z28.object({typeName:z28.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z28.object({id:z28.string(),name:z28.string(),type:z28.enum(["file","folder"]),mimeType:z28.string().nullable(),storageKey:z28.string().nullable(),url:z28.string().nullable(),fileSize:z28.number().nullable(),width:z28.number().nullable(),height:z28.number().nullable(),altText:z28.string().nullable(),caption:z28.string().nullable(),createdAt:z28.coerce.date(),updatedAt:z28.coerce.date()}),AssetDiffSchema=z28.object({assetId:z28.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z28.object({locale:z28.string(),key:z28.string(),parent:z28.string().nullable(),child:z28.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z28.object({formName:z28.string(),label:z28.string().nullable(),schemaFingerprint:z28.string(),fields:z28.record(z28.string(),z28.unknown()),settings:z28.record(z28.string(),z28.unknown()).optional()}),FormSchemaDiffSchema=z28.object({formName:z28.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z28.object({agentName:z28.string(),triggerIndex:z28.number().int().nonnegative(),triggerKind:z28.string(),triggerSpec:z28.record(z28.string(),z28.unknown()),enabled:z28.boolean(),emailRecipients:z28.array(z28.string()).nullable(),qstashScheduleId:z28.string().nullable()}),ActivationDiffSchema=z28.object({agentName:z28.string(),triggerIndex:z28.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),ConflictSchema=z28.object({surface:SurfaceNameSchema,key:z28.string(),kind:z28.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity"]).optional(),description:z28.string(),parentValue:z28.unknown().optional(),childValue:z28.unknown().optional(),conflictingFields:z28.array(z28.string()).optional(),code:z28.object({path:z28.string(),unresolvable:z28.boolean().optional(),reason:z28.string().optional()}).optional()}),FieldPickSchema=z28.object({field:z28.string(),choice:z28.enum(["parent","child","pick","ai-pick"]),pickedValue:z28.unknown().optional(),aiSessionId:z28.string().optional()}),ConflictResolutionSchema=z28.object({surface:SurfaceNameSchema,key:z28.string(),choice:z28.enum(["parent","child","pick"]),pickedValue:z28.unknown().optional(),fieldPicks:z28.array(FieldPickSchema).optional()}),MergeResultSchema=z28.object({ok:z28.boolean(),mergeId:z28.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z28.array(z28.object({surface:SurfaceNameSchema,count:z28.number().int().nonnegative()})),conflicts:z28.array(ConflictSchema).optional(),summary:z28.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z28.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z28.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z28.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z28.boolean().optional()}),ResolvedStrategySchema=z28.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z28.boolean()}),MergeRequestSchema=z28.object({from:EnvSchema,allowDirectMerge:z28.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z28.object({mergeId:z28.string().uuid(),streamUrl:z28.string(),strategy:ResolvedStrategySchema,acceptedAt:z28.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z28.object({mergeId:z28.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z28.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z28.array(ConflictSchema),draftResolutions:z28.array(ConflictResolutionSchema),lastEditedBy:z28.string().nullable(),lastEditedAt:z28.coerce.date().nullable(),initiator:z28.object({userId:z28.string().nullable(),role:z28.string().nullable(),agentName:z28.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z28.object({resolutions:z28.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z28.object({mergeId:z28.string().uuid(),draftResolutions:z28.array(ConflictResolutionSchema),lastEditedAt:z28.coerce.date(),lastEditedBy:z28.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z28.object({mergeId:z28.string().uuid(),resolutions:z28.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z28.object({mergeId:z28.string().uuid()}),PublishReleaseRequestSchema=z28.object({version:z28.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z28.string().max(2e4).optional()}),PublishReleaseResultSchema=z28.object({releaseTag:z28.string(),sha:z28.string(),publishedAt:z28.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z29}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z29.object({surface:SurfaceNameSchema,key:z29.string(),label:z29.string()}),InlineSchema=z29.object({text:z29.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z29.discriminatedUnion("type",[z29.object({type:z29.literal("paragraph"),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("preview"),ref:DiffRefSchema,caption:z29.string().optional()}),z29.object({type:z29.literal("code"),code:z29.string(),lang:z29.string().optional(),caption:z29.string().optional()}),z29.object({type:z29.literal("risk"),level:z29.enum(["warning","error"]),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("list"),items:z29.array(z29.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z29.object({headline:z29.string(),blocks:z29.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z29.object({summary:EnvDiffSummarySchema,fingerprint:z29.string(),generatedAt:z29.coerce.date(),cached:z29.boolean().optional(),credits:z29.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z30}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z30.object({date:z30.string(),visitors:z30.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z30.object({key:z30.string(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z30.object({path:z30.string(),pageName:z30.string().nullable().optional(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z30.object({preset:z30.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z30.string(),requestedTo:z30.string(),effectiveFrom:z30.string(),effectiveTo:z30.string(),isRetentionLimited:z30.boolean(),groupBy:z30.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z30.object({date:z30.string(),content:z30.string(),updatedAt:z30.string(),updatedByUserId:z30.string()}),ProjectPageviewAnalyticsDTOSchema=z30.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative(),bounceRate:z30.number().min(0).max(100),viewsPerVisit:z30.number().nonnegative(),averageVisitDurationSeconds:z30.number().nonnegative(),visitorsSeries:z30.array(ProjectDailyVisitorsDTOSchema),topPages:z30.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z30.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z31}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z31.object({id:z31.string(),email:z31.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z31.coerce.date(),createdAt:z31.coerce.date(),inviterUserId:z31.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z31.object({id:z31.string(),token:z31.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z31.object({success:z31.boolean(),projectId:z31.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z32}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z32.object({id:z32.string(),name:z32.string(),image:z32.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z32.object({count:z32.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z32.object({counts:z32.object({signed_up:z32.int(),activated:z32.int()}),credits:z32.object({total:z32.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z32.email(),emailVerified:z32.boolean(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z33}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z33.object({id:z33.string(),principalType:ProjectPrincipalTypeSchema,principalId:z33.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z33.coerce.date(),expiresAt:z33.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z33.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z33.record(z33.string(),z33.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z33.object({access:z33.array(ProjectAccessItemDTOSchema),invites:z33.array(ProjectInviteDTOSchema),organization:z33.object({name:z33.string().nullable(),logo:z33.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z33.object({success:z33.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z33.object({success:z33.boolean(),projectId:z33.uuid()}))}});import{z as z34}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z34.object({publicationStatus:PublicationStatusSchema,appUrl:z34.string().nullable(),lastPublishedAt:z34.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z35}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewBootstrapDTOSchema,PreviewBootstrapDTO,PreviewBootstrapResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z35.object({url:z35.url(),expiresAt:z35.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z35.discriminatedUnion("source",[z35.object({source:z35.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z35.null()}),z35.object({source:z35.literal("dev"),artifact:z35.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z36}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z36.string(),slug:z36.string().nullable(),logo:z36.string().nullable(),metadata:z36.record(z36.string(),z36.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z36.object({id:z36.string(),name:z36.string(),email:z36.email(),image:z36.string().nullable()}),OrganizationMemberDTOSchema=z36.object({id:z36.string(),userId:z36.string(),organizationId:z36.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z36.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z37}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z37.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z37.object({reason:CancellationReasonCodeSchema,details:z37.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z37.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z37.object({included:z37.number().optional(),unitPrice:z37.number().optional(),dailyCap:z37.number().nullable().optional()}),EntitlementsDTOSchema=z37.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z37.object({retentionDays:z37.number().int().positive(),canUseExtendedDateRanges:z37.boolean()}).optional(),members:z37.object({canInvite:z37.boolean(),maxMembers:z37.number().int().positive().nullable()}).optional(),projects:z37.object({canCreatePrivateProjects:z37.boolean(),maxPrivateProjects:z37.number().int().positive().nullable()}).optional(),domains:z37.object({canUseCustomDomains:z37.boolean(),maxDomains:z37.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z37.object({id:z37.string(),external_id:z37.string(),customerId:z37.string(),planId:z37.string(),planCode:TemplateCodeSchema,currentPeriod:z37.object({start:z37.string(),end:z37.string().nullable()}),cancelAt:z37.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z37.string(),nextPaymentAt:z37.string().nullable(),baseAmount:z37.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z37.object({totalCap:z37.number(),dailyCap:z37.number(),usedTotal:z37.number()}),CreditBalanceDTOSchema=z37.object({total:z37.number(),base:z37.number(),dailyBase:z37.number(),purchases:z37.number(),awards:z37.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z37.object({total:z37.number(),nearLimit:z37.boolean(),canChat:z37.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z37.object({dailyFreeAvailable:z37.number(),monthlyAvailable:z37.number(),purchasedAvailable:z37.number(),awardedAvailable:z37.number()}),ProjectDailyCreditAllowanceDTOSchema=z37.object({periodCap:z37.number(),dailyGrant:z37.number(),usedThisPeriod:z37.number(),remainingThisPeriod:z37.number()}),ProjectCreditBalanceDTOSchema=z37.object({projectId:z37.uuid(),organizationId:z37.string(),balance:z37.object({totalAvailable:z37.number(),nearLimit:z37.boolean(),canUseAi:z37.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z37.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z37.object({invoiceId:z37.string(),newBalance:z37.int(),creditCount:z37.int(),amountUsd:z37.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z37.object({url:z37.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z38}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z38.object({brand:z38.string(),last4:z38.string(),exp:z38.string(),isDefault:z38.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z39}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z39.string().superRefine((path64,ctx)=>{let segments=path64.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z39.object({type:z39.literal("renameField"),contentType:z39.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z39.object({enabled:z39.boolean()}).strict(),ContentTypeDTOSchema=z39.object({id:z39.string(),name:z39.string(),label:z39.string(),isSingleton:z39.boolean(),i18n:ContentTypeI18nSchema,fields:z39.record(z39.string(),FieldDefinitionSchema),createdAt:z39.string(),updatedAt:z39.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z39.object({contentTypes:z39.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z39.object({id:z39.string(),entryId:z39.string(),documentId:z39.string(),slug:z39.string(),locale:z39.string().optional(),createdAt:z39.string(),updatedAt:z39.string(),__fimo:z39.object({contentType:z39.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({limit:z39.number(),offset:z39.number(),total:z39.number(),hasMore:z39.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z39.object({contentType:z39.string(),count:z39.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z39.object({counts:z39.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z39.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z39.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z39.union([z39.string(),z39.number(),z39.boolean(),z39.null()]),entryWhereOperatorSchema=z39.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z39.array(entryWhereScalarSchema).optional(),$nin:z39.array(entryWhereScalarSchema).optional(),$contains:z39.string().optional(),$startsWith:z39.string().optional(),$null:z39.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z39.object({data:z39.record(z39.string(),z39.unknown()),locale:z39.string().min(1).optional(),documentId:z39.uuid().optional()}),entryIdsSchema=z39.array(z39.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z39.object({sql:z39.string().min(1)}),BulkCreateEntriesRequestSchema=z39.object({entries:z39.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z39.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z39.object({updates:z39.array(z39.object({id:z39.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,locale:z39.string().min(1).optional()}),z39.object({where:EntryWhereSchema,locale:z39.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z39.object({data:z39.array(z39.record(z39.string(),z39.unknown())),meta:z39.object({rowCount:z39.number().int().nonnegative(),truncated:z39.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({created:z39.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({updated:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({deleted:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z40}from"zod";var 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=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z40.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z40.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z40.object({field:CmsFieldNameSchema,direction:z40.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z40.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z40.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z40.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z40.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z40.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z41}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=z41.object({id:z41.string(),name:z41.string()}),AssetDTOSchema=z41.object({id:z41.string(),name:z41.string(),type:AssetTypeSchema,originalFileName:z41.string().nullable(),parentId:z41.string().nullable(),mimeType:z41.string().nullable(),fileSize:z41.number().nullable(),url:z41.string().nullable(),storageKey:z41.string().nullable(),createdAt:z41.string(),updatedAt:z41.string(),altText:z41.string().nullable().optional(),caption:z41.string().nullable().optional(),aiCaption:z41.string().nullable().optional(),aiAltText:z41.string().nullable().optional(),aiTags:z41.array(z41.string()).nullable().optional(),aiPrimaryColor:z41.string().nullable().optional(),aiProcessingStatus:z41.string().nullable().optional(),width:z41.number().nullable().optional(),height:z41.number().nullable().optional(),path:z41.array(AssetPathItemSchema).optional(),hasChildren:z41.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z41.lazy(()=>z41.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z41.array(AssetDTOSchema))}});import{z as z42}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z42.object({key:z42.string(),value:z42.string().optional(),defaultValue:z42.string(),locale:z42.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z43}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=z43.object({id:z43.string(),name:z43.string(),type:z43.enum(["file","folder"]),path:z43.string(),children:z43.lazy(()=>z43.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z43.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z43.object({path:z43.string(),exists:z43.boolean(),type:z43.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z44}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z44.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z44.object({items:z44.array(ProjectMessagePublicDTOSchema),nextCursor:z44.string().nullable()}),ChatDeletionDTOSchema=z44.object({success:z44.boolean(),deletedCount:z44.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z45}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=z45.object({url:z45.string().url(),key:z45.string(),size:z45.number(),contentType:z45.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z46}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=z46.object({canAccess:z46.boolean(),permissions:z46.record(z46.string(),z46.boolean()),role:z46.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z47}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:z47.string().trim().default(""),sort:z47.enum(["recent","name","relevance"]).default("recent"),category:z47.string().optional(),visibility:z47.enum(["public","private"]).optional()})}});import{z as z48}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=z48.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z48.enum(["fimo","external"]),PaymentStatusSchema=z48.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z48.object({id:z48.string().uuid(),domain:z48.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z48.boolean(),price:z48.number().int().nullable(),renewalPrice:z48.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z48.string().nullable(),failureReason:z48.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z48.object({domain:z48.string(),available:z48.boolean(),premium:z48.boolean(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),purchaseType:z48.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z48.object({domain:z48.string(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),premium:z48.boolean(),allowedYears:z48.array(z48.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z48.object({firstName:z48.string().max(100),lastName:z48.string().max(100),companyName:z48.string().max(100).optional(),address1:z48.string().max(255),address2:z48.string().max(255).optional(),city:z48.string().max(100),state:z48.string().max(100),zip:z48.string().max(20),country:z48.string().max(2),phone:z48.string().max(30),email:z48.union([z48.string().email().max(255),z48.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z48.object({firstName:z48.string().min(1).max(100),lastName:z48.string().min(1).max(100),companyName:z48.string().max(100).optional(),address1:z48.string().min(1).max(255),address2:z48.string().max(255).optional(),city:z48.string().min(1).max(100),state:z48.string().min(1).max(100),zip:z48.string().min(1).max(20),country:z48.string().min(1).max(2),phone:z48.string().min(1).max(30),email:z48.string().email().max(255)}),SearchDomainsRequestSchema=z48.object({keyword:z48.string().min(1).max(100),tldFilter:z48.array(z48.string()).optional()}),CheckAvailabilityRequestSchema=z48.object({domains:z48.array(z48.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=z48.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z48.object({domain:DomainNameSchema,years:z48.number().int().min(1).max(10).optional().default(3),autoRenew:z48.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z48.object({autoRenew:z48.boolean().optional()}),RenewDomainRequestSchema=z48.object({years:z48.number().int().min(1).max(10).optional().default(1),autoRenew:z48.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z48.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z48.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z48.object({verified:z48.boolean(),email:z48.string().nullable(),verifyBy:z48.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z49}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=z49.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=z49.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=z49.object({txtName:z49.string().nullable().optional(),txtValue:z49.string().nullable().optional(),httpUrl:z49.string().nullable().optional(),httpBody:z49.string().nullable().optional(),cname:z49.string().nullable().optional(),cnameTarget:z49.string().nullable().optional()}),SSLValidationErrorSchema=z49.object({message:z49.string()}),OwnershipVerificationSchema=z49.object({type:z49.string(),name:z49.string(),value:z49.string()}),ProjectDomainSSLDTOSchema=z49.object({status:z49.string(),method:z49.string().nullable(),type:z49.string().nullable(),validationRecords:z49.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z49.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z49.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z49.enum(["subdomain","apex"]),RedirectConfigSchema=z49.object({type:z49.literal("apex_to_www"),linkedDomainId:z49.string()}).nullable().optional(),ProjectDomainDTOSchema=z49.object({id:z49.string(),hostname:z49.string(),status:z49.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z49.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z49.string(),scdCnameTarget:z49.string().optional(),apexTargets:z49.array(z49.string()),dnsAutoConfigured:z49.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z49.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z49.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z49.object({hostname:z49.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:z49.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z49.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z49.object({success:z49.boolean(),hostname:z49.string()}))}});import{z as z50}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=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z50.object({available:z50.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z50.object({slug:z50.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z50.object({subdomain:z50.string(),subdomainUpdatedAt:z50.coerce.date()})),SubdomainSuggestionsQuerySchema=z50.object({base:z50.string().max(100).optional(),max:z50.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z50.object({suggestions:z50.array(z50.string())}))}});import{z as z51}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=z51.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z51.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=z51.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z51.number(),credits:z51.number().optional(),billingMode:z51.enum(["fimo-credits","provider-account"]).optional(),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z52}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=z52.object({options:z52.record(z52.string(),z52.unknown()),name:z52.string().optional(),parentId:z52.string().nullable().optional(),altText:z52.string().optional(),caption:z52.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z52.string().min(1).optional(),model:z52.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=z52.object({jobId:z52.string(),status:z52.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z52.string().nullable().optional(),credits:z52.number().optional(),costUsd:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z52.object({error:z52.string(),code:z52.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:z52.array(GenerationTaskIdSchema).optional(),availableModels:z52.array(z52.string()).optional(),issues:z52.array(z52.unknown()).optional()})}});import{z as z53}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=z53.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z53.object({name:z53.string(),key:z53.string(),description:z53.string(),type:FlagTypeSchema,required:z53.boolean(),defaultValue:z53.unknown().optional(),enumValues:z53.array(z53.string()).optional(),isArray:z53.boolean()}),AssetModelPriceSchema=z53.object({unitPrice:z53.number(),unit:z53.string(),confidence:z53.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z53.object({id:z53.string(),shortName:z53.string(),provider:z53.string(),source:z53.string(),modality:z53.enum(["image","video","audio"]),tags:z53.array(z53.string()),displayName:z53.string(),description:z53.string(),flags:z53.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z53.object({model:z53.string(),costUsd:z53.number(),credits:z53.number(),billingMode:z53.enum(["fimo-credits","provider-account"]),confidence:z53.enum(["exact","estimated","metered"]),basis:z53.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z54}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=z54.object({tourId:z54.string(),version:z54.string(),status:z54.string(),completedAt:z54.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z54.array(UserTourDTOSchema))}});import{z as z55}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=z55.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z55.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z55.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z55.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z55.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z55.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z55.enum(["user","agent","system"]),SupportReportTagSchema=z55.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z55.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z55.object({organization:z55.object({id:z55.string().trim().min(1).max(255),name:z55.string().trim().max(240).optional()}),project:z55.object({id:z55.uuid(),name:z55.string().trim().max(240).optional(),createdAt:z55.coerce.date().optional()}).optional(),environment:z55.string().trim().max(255).optional(),clientVersion:z55.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z55.object({message:z55.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z55.string().trim().max(200).optional(),limit:z55.coerce.number().int().min(1).max(100).default(50),offset:z55.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z55.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z55.uuid().nullable().optional(),note:z55.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=z55.object({message:z55.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z55.object({kind:SupportReportLinkKindSchema,label:z55.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z55.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z55.object({kind:SupportReportActorKindSchema,id:z55.string().nullable(),name:z55.string().nullable()}),SupportReportLinkDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportLinkKindSchema,label:z55.string(),url:SupportReportHttpUrlSchema,externalId:z55.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportEventKindSchema,body:z55.string().nullable(),metadata:z55.record(z55.string(),z55.unknown()),actor:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z55.object({id:z55.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z55.array(z55.string()),source:SupportReportSourceSchema,message:z55.string(),reporter:z55.object({id:z55.string().nullable(),name:z55.string().nullable(),email:z55.string().nullable()}),organization:z55.object({id:z55.string().nullable(),name:z55.string()}),project:z55.object({id:z55.uuid().nullable(),name:z55.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z55.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z55.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z55.string().nullable(),deliveredAt:z55.coerce.date().nullable()}).nullable(),duplicateOfReportId:z55.uuid().nullable(),resolvedAt:z55.coerce.date().nullable(),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z55.string().nullable(),clientVersion:z55.string().nullable(),links:z55.array(SupportReportLinkDTOSchema),events:z55.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z55.object({reports:z55.array(SupportReportSummaryDTOSchema),total:z55.number().int().nonnegative(),statusCounts:z55.object({new:z55.number().int().nonnegative(),in_progress:z55.number().int().nonnegative(),waiting:z55.number().int().nonnegative(),resolved:z55.number().int().nonnegative(),duplicate:z55.number().int().nonnegative(),irrelevant:z55.number().int().nonnegative(),ignored:z55.number().int().nonnegative()}),limit:z55.number().int().positive(),offset:z55.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z55.object({id:z55.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z55.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z56}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=z56.iso.datetime({offset:!0}).pipe(z56.coerce.date()),OpsRecentChatInputSchema=z56.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z56.string().trim().min(1).max(255).optional(),limit:z56.coerce.number().int().min(1).max(200).default(100),cursor:z56.string().trim().min(1).max(2e3).optional(),slim:z56.boolean().default(!0),reason:z56.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=z56.object({id:z56.string(),messageId:z56.string(),env:z56.string(),versionId:z56.string().nullable(),userId:z56.string().nullable(),role:z56.string(),parts:z56.array(z56.record(z56.string(),z56.unknown())),metadata:z56.object({status:z56.string().optional(),traceUrl:z56.string().optional(),externalFileChanges:z56.array(z56.unknown()).optional()}),stats:z56.object({toolCount:z56.number().int().nonnegative(),failedToolCount:z56.number().int().nonnegative()}),createdAt:z56.iso.datetime({offset:!0}),project:z56.object({id:z56.string(),name:z56.string(),displayName:z56.string().nullable(),organizationId:z56.string().nullable()})}),OpsRecentChatResponseSchema=z56.object({target:z56.object({backendProfile:OpsBackendProfileSchema,projectEnv:z56.string().nullable()}),window:z56.object({from:z56.iso.datetime({offset:!0}),to:z56.iso.datetime({offset:!0})}),messages:z56.object({items:z56.array(OpsRecentChatMessageSchema),nextCursor:z56.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z57}from"zod";function createAgentRunWebhookEventDataSchema(status){return z57.object({run:z57.object({id:z57.string(),agentName:z57.string(),trigger:z57.string(),status:z57.literal(status),startedAt:z57.string().nullable(),finishedAt:z57.string().nullable(),reason:z57.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,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_create_dto();init_response();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"],WebhookEventTypeSchema=z57.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z57.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z57.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z57.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z57.union([z57.literal(0),z57.literal(5),z57.literal(30),z57.literal(60)]),EntryChangedWebhookEventDataSchema=z57.object({reason:WebhookEntryChangeReasonSchema,operationId:z57.string().optional(),batch:z57.object({index:z57.number().int().positive(),total:z57.number().int().positive()}).optional(),changes:z57.array(z57.object({action:WebhookEntryChangeActionSchema,contentType:z57.string(),id:z57.string(),documentId:z57.string(),locale:z57.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z57.object({form:z57.object({id:z57.string(),label:z57.string()}),submission:z57.object({id:z57.string(),data:z57.record(z57.string(),z57.unknown()),submittedAt:z57.string()})}),PublishStartedWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("publishing"),startedAt:z57.string()})}),PublishSucceededWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("published"),url:z57.string(),publishedAt:z57.string(),firstPublish:z57.boolean()})}),PublishFailedWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("failed"),reason:z57.string()})}),PublishUnpublishedWebhookEventDataSchema=z57.object({publication:z57.object({previousUrl:z57.string(),unpublishedAt:z57.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z57.object({review:z57.object({id:z57.string(),runId:z57.string(),agentName:z57.string(),classification:z57.string(),summary:z57.string(),reasons:z57.array(z57.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z57.object({review:z57.object({id:z57.string(),runId:z57.string(),agentName:z57.string(),resolution:z57.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z57.object({report:z57.object({weekStart:z57.string(),weekEnd:z57.string(),pageviews:z57.number(),visitors:z57.number(),previousPageviews:z57.number(),previousVisitors:z57.number()})}),MediaAssetWebhookEventDataSchema=z57.object({id:z57.string().nullable(),name:z57.string().nullable(),type:z57.string(),mimeType:z57.string().nullable(),fileSize:z57.number().nullable()}),MediaUploadedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.enum(["updated","moved","analysis"]),analysis:z57.object({category:z57.string(),status:z57.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("generated"),generation:z57.object({model:z57.string(),mode:z57.string()})}),MediaProcessingFailedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.enum(["analysis","generation"]),failure:z57.object({code:z57.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},WebhookEventFamilySchema=z57.enum(["entries","forms","publish","agents","analytics","media"]),WebhookDestinationKindSchema=z57.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z57.discriminatedUnion("source",[z57.object({source:z57.literal("literal"),value:z57.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z57.object({source:z57.literal("secret"),key:z57.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z57.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z57.object({name:z57.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z57.object({name:z57.string(),source:z57.enum(["literal","secret"]),secretKey:z57.string().nullable(),secretPrefix:z57.string().nullable(),configured:z57.literal(!0)}),WebhookFilterSchema=z57.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z57.string().min(1).max(255).optional(),agentName:z57.string().min(1).max(120).optional(),mediaType:z57.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z57.string().min(1).max(255).optional(),locale:z57.string().min(1).max(120).optional()}),JsonValueSchema=z57.lazy(()=>z57.union([z57.string(),z57.number(),z57.boolean(),z57.null(),z57.array(JsonValueSchema),z57.record(z57.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z57.object({name:z57.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z57.url(),enabled:z57.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z57.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z57.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z57.object({name:z57.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z57.url().optional(),enabled:z57.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z57.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z57.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z57.object({eventType:WebhookEventTypeSchema.optional(),data:z57.record(z57.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z57.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z57.uuid(),name:z57.string(),eventType:WebhookEventTypeSchema,enabled:z57.boolean(),destination:z57.object({host:z57.string(),maskedUrl:z57.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z57.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z57.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z57.coerce.date().nullable(),deliveryStats24h:z57.object({succeeded:z57.number().int().nonnegative(),failed:z57.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z57.uuid(),projectId:z57.uuid(),env:EnvSchema,eventId:z57.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z57.number().int().positive(),test:z57.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z57.number().int().nonnegative(),responseStatus:z57.number().int().nullable(),lastErrorCode:z57.string().nullable(),lastErrorMessage:z57.string().nullable(),payloadAvailable:z57.boolean(),destination:z57.object({host:z57.string(),maskedUrl:z57.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z57.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z57.string().nullable(),qstashMessageId:z57.string().nullable(),deliveredAt:z57.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z57.object({items:z57.array(WebhookDeliveryDTOSchema),pagination:z57.object({page:z57.number().int().positive(),limit:z57.number().int().positive(),total:z57.number().int().nonnegative(),totalPages:z57.number().int().positive(),hasMore:z57.boolean()}),stats:z57.object({total:z57.number().int().nonnegative(),succeeded:z57.number().int().nonnegative(),failed:z57.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z57.object({id:z57.uuid(),deliveryId:z57.uuid(),attempt:z57.number().int().positive(),status:z57.enum(["delivering","succeeded","failed"]),responseStatus:z57.number().int().nullable(),durationMs:z57.number().int().nonnegative(),responseExcerpt:z57.string().nullable(),errorCode:z57.string().nullable(),errorMessage:z57.string().nullable(),createdAt:z57.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z57.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z57.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z58}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=z58.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z58.object({total:z58.number(),base:z58.number(),purchases:z58.number(),awards:z58.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z58.object({id:z58.string(),name:z58.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z58.object({type:z58.string(),brand:z58.string().nullable(),last4:z58.string().nullable(),expirationDate:z58.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z58.object({currency:z58.string(),nextPaymentAmount:z58.number().nullable(),nextPaymentAt:z58.string().nullable(),billingInterval:z58.string().nullable(),totalAmount:z58.number().nullable(),discountAmount:z58.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z58.object({id:z58.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z58.string().nullable(),currentPeriodEndsAt:z58.string().nullable(),renewsAt:z58.string().nullable(),cancelAt:z58.string().nullable(),renewAutomatically:z58.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z58.object({type:z58.enum(["low_balance","critical_balance","approaching_limit"]),message:z58.string(),estimatedPromptsRemaining:z58.number().nullable(),avgCostPerPrompt:z58.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z58.object({monthlyCredits:z58.number().nullable(),usedThisPeriod:z58.number(),remainingThisPeriod:z58.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z58.object({organizationId:z58.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z58.string().nullable(),tenureDays:z58.number().int().nonnegative(),capturedAt:z58.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z58.object({hasSubscription:z58.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z58.number().nullable(),alerts:z58.array(CreditAlertDTOSchema),portalUrl:z58.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z58.object({creditCount:z58.number().int().positive(),expiresAt:z58.string().datetime().nullable().optional(),message:z58.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z58.literal("free"),amountCents:z58.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z58.literal("purchase"),amountCents:z58.number().int().positive()}),CreditTopupRequestDTOSchema=z58.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z58.object({success:z58.boolean(),transactionId:z58.string().nullable(),newBalance:z58.number(),creditCount:z58.number(),type:z58.enum(["free","purchase"]),invoiceId:z58.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z59}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=z59.object({totalCredits:z59.number(),totalCostUsd:z59.number(),totalMessages:z59.number(),avgCostPerMessage:z59.number(),periodStart:z59.string().nullable(),periodEnd:z59.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().email().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z59.object({date:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().email().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z59.array(UsageByUserForProjectDTOSchema),timeline:z59.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z59.object({summary:UsageSummaryDTOSchema,byProject:z59.array(UsageByProjectDTOSchema),byUser:z59.array(UsageByUserDTOSchema),timeline:z59.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z60}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=z60.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z60.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z60.object({startDate:z60.string().optional(),endDate:z60.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z60.coerce.number().int().positive().default(1),limit:z60.coerce.number().int().positive().max(100).default(20),sortBy:z60.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z60.string().optional()}),UsageOverviewSummaryDTOSchema=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),avgCreditsPerMessage:z60.number(),periodStart:z60.string(),periodEnd:z60.string(),creditsChange:z60.number().nullable(),costChange:z60.number().nullable(),messagesChange:z60.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z60.object({organizationId:z60.string(),organizationName:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),userCount:z60.number(),projectCount:z60.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().nullable(),userImage:z60.string().nullable(),organizationId:z60.string().nullable(),organizationName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),projectCount:z60.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),organizationId:z60.string(),organizationName:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),userCount:z60.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z60.object({id:z60.string(),name:z60.string(),value:z60.number(),percentage:z60.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z60.object({day:z60.number(),hour:z60.number(),value:z60.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z60.object({summary:UsageOverviewSummaryDTOSchema,timeline:z60.array(UsageTimelinePointDTOSchema),topOrganizations:z60.array(OrganizationUsageRowDTOSchema),topUsers:z60.array(UserUsageRowDTOSchema),topProjects:z60.array(ProjectUsageRowDTOSchema),creditDistribution:z60.array(UsageDistributionItemDTOSchema),heatmap:z60.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z60.object({page:z60.number(),limit:z60.number(),totalItems:z60.number(),totalPages:z60.number(),hasMore:z60.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z60.object({organizations:z60.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z60.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z60.object({users:z60.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z60.string(),ownerName:z60.string().nullable(),ownerEmail:z60.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z60.object({projects:z60.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z60.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z60.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z60.object({credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z60.object({id:z60.string(),name:z60.string(),createdAt:z60.string(),memberCount:z60.number(),projectCount:z60.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z60.object({id:z60.string(),name:z60.string().nullable(),email:z60.string(),image:z60.string().nullable(),createdAt:z60.string(),organizationCount:z60.number(),projectCount:z60.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z60.object({id:z60.string(),name:z60.string(),displayName:z60.string().nullable(),createdAt:z60.string(),organizationId:z60.string(),organizationName:z60.string(),ownerId:z60.string(),ownerName:z60.string().nullable(),ownerEmail:z60.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z61}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=z61.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z61.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z61.object({command:z61.string().min(1).max(1e4),cwd:z61.string().optional(),projectEnv:EnvSchema.optional(),env:z61.record(z61.string(),z61.string()).optional(),name:z61.string().optional(),waitForCompletion:z61.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z61.object({identifier:z61.string(),status:SandboxProcessStatusSchema,command:z61.string().optional(),startedAt:z61.string().optional(),exitCode:z61.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z61.object({processes:z61.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z61.object({processId:z61.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z61.object({success:z61.boolean(),message:z61.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z62}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_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_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit2(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit2(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit2(["status","--porcelain"],cwd)).length>0}async function cloneRepo2(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit2(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit2(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit2,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo2,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});var project_context_exports={};__export(project_context_exports,{EnvNotFoundError:()=>EnvNotFoundError,GitBranchUndetectedError:()=>GitBranchUndetectedError,InvalidEnvOverrideError:()=>InvalidEnvOverrideError,NotInProjectError:()=>NotInProjectError,bootstrapProjectCommand:()=>bootstrapProjectCommand,envOverrideFromCommand:()=>envOverrideFromCommand,envSourceBanner:()=>envSourceBanner,getProjectContext:()=>getProjectContext,projectConfig:()=>projectConfig});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveEnvFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{env:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||branch==="HEAD"||!isValidEnv(branch)?null:{env:branch,source:"branch"}}catch{return null}}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let env,source,readOnly=!1;if(opts.envOverride!==void 0){if(!isValidEnv(opts.envOverride))throw new InvalidEnvOverrideError(opts.envOverride);env=opts.envOverride,source="flag"}else{let fromGit=await resolveEnvFromGit(cwd);if(fromGit)env=fromGit.env,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{if(opts.requireBranch)throw await isGitRepo(cwd)?new GitBranchUndetectedError:new NotInProjectError;env=DEFAULT_ENV,source="fallback"}}if(opts.api&&env!=="prod")try{let names=(await opts.api.listEnvs(settings.projectId)).map(e=>e.env);if(!names.includes(env)&&source==="flag")throw new EnvNotFoundError(env,names)}catch(err){if(err instanceof EnvNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,env,source,readOnly:readOnly||void 0}}function envSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--env":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"default",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 env: ${ctx.env} (from ${sourceHint}${ro})`}function envOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let env=cur.opts().env;if(typeof env=="string"&&env.length>0)return env;cur=cur.parent??null}}function projectConfig(ctx){return configForApiUrl(ctx.apiUrl)}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let envOverride2=envOverrideFromCommand(cmd),baseApi=new FimoApiClient(loadConfig()),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,requireBranch:bootstrapOpts.requireBranch,api:baseApi}),cfg=configForApiUrl(ctx.apiUrl),projectApi=ctx.apiUrl&&ctx.apiUrl!==loadConfig().apiUrl?new FimoApiClient(cfg):baseApi;if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
436
+ `)}function renderCliAuthError(err,opts={}){console.error(formatCliAuthError(err,opts))}function formatShellArg(arg){return/^[A-Za-z0-9_/:=.,@%+-]+$/.test(arg)?arg:`'${arg.replace(/'/g,"'\\''")}'`}var init_auth_errors=__esm({"src/cli/utils/auth-errors.ts"(){init_api();init_auth();init_color();__name(isCliAuthError,"isCliAuthError");__name(rethrowCliAuthError,"rethrowCliAuthError");__name(retryCommand,"retryCommand");__name(formatCliAuthError,"formatCliAuthError");__name(renderCliAuthError,"renderCliAuthError");__name(formatShellArg,"formatShellArg")}});import{z as z7}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z7.ZodOptional||schema instanceof z7.ZodNullable||schema instanceof z7.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z7.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z7.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 z7.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z7.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],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z7.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 z7.ZodObject)return createObjectDTO(schema);if(schema instanceof z7.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 z8}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z8.object({data:dataSchema}),"createResponseSchema")}});import{z as z9}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z9.object({page:z9.coerce.number().int().positive().default(1),limit:z9.coerce.number().int().positive().max(100).default(20)})}});import{z as z10}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,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:z10.coerce.date(),positiveInt:z10.number().int().positive(),nonNegativeInt:z10.number().int().nonnegative()},BaseEntitySchema=z10.object({id:z10.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z10.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z10.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z10.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z10.enum(["public","private"]),ProjectStatusSchema=z10.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z10.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z10.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z10.enum(["owner","admin","member"]),AssetTypeSchema=z10.enum(["file","folder"]),TemplateCodeSchema=z10.enum(["Free","Premium"]),FieldTypeSchema=z10.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],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_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]))}});import{z as z11}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z11.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z12}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 ReferenceValueSchema,PolymorphicReferenceValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");ReferenceValueSchema=z12.preprocess(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({documentId:z12.uuid()}));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");PolymorphicReferenceValueSchema=z12.preprocess(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({contentType:z12.string().min(1),documentId:z12.uuid()}))}});import{z as z13}from"zod";function rejectFieldLocaleSettings(field,ctx){for(let key of["i18n","localized"])key in field&&ctx.addIssue({code:"custom",path:[key],message:"Field-level locale settings are not supported."})}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk2=__name((currentFields,path64,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path64,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)walk2(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk2(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk2(fields,[],0,!1)}var MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,commonFieldShape,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();MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],commonFieldShape={label:z13.string().min(1).optional(),description:z13.string().optional(),editable:z13.boolean().optional(),required:z13.boolean().optional(),default:z13.unknown().optional()};__name(rejectFieldLocaleSettings,"rejectFieldLocaleSettings");scalarFieldSchema=z13.object({...commonFieldShape,type:z13.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z13.number().optional(),max:z13.number().optional(),minLength:z13.number().int().nonnegative().optional(),maxLength:z13.number().int().nonnegative().optional(),regex:z13.string().optional(),multiple:z13.boolean().optional(),allowedMimeTypes:z13.array(z13.string()).optional()}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(field,ctx);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.`})}),referenceFieldSchema=z13.object({...commonFieldShape,type:z13.literal("reference"),target:z13.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z13.array(z13.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z13.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(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"])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=z13.lazy(()=>contentFieldDefinitionSchema),blockFieldsSchema=z13.record(z13.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.`})}),blockVariantSchema=z13.object({uid:z13.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z13.string().min(1),description:z13.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z13.object({fields:blockFieldsSchema}).strict(),blocksSchema=z13.object({oneOf:z13.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=z13.object({...commonFieldShape,type:z13.literal("blocks"),min:z13.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z13.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z13.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(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"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z13.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z14}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","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z14.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z14.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z14.enum(AUDIT_ACTOR_KINDS)}});import{z as z15}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,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z15.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z15.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","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:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers: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=z15.object({permissions:z15.array(OpsPermissionSchema).min(1),backendProfiles:z15.array(OpsBackendProfileSchema).min(1),enabled:z15.boolean().default(!0)}),OpsServiceTokenInputSchema=z15.object({name:z15.string().trim().min(1).max(120),permissions:z15.array(OpsPermissionSchema).min(1),backendProfiles:z15.array(OpsBackendProfileSchema).min(1),expiresAt:z15.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=z15.object({importanceReason:z15.string().trim().min(1).max(1e3),ownerUserId:z15.string().trim().min(1).nullable().optional(),framework:z15.string().trim().max(120).nullable().optional(),packageManager:z15.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z15.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z15.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z15.object({projectId:z15.uuid(),title:z15.string().trim().min(1).max(240),userReport:z15.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z15.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z15.string().trim().max(1e4).nullable().optional(),outcome:z15.string().trim().max(1e4).nullable().optional(),evidence:z15.array(z15.record(z15.string(),z15.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=z15.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z15.object({fingerprint:z15.string().trim().min(1).max(240),title:z15.string().trim().min(1).max(240),description:z15.string().trim().min(1).max(1e4),affectedVersions:z15.array(z15.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z15.array(z15.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z15.string().trim().min(1).max(64).nullable().optional(),workaround:z15.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z15.array(z15.string().trim().min(1).max(120)).max(100),detectionQueries:z15.array(z15.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=z15.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z15.object({changeReference:z15.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z15.string().trim().min(1).max(1e4),evidence:z15.array(z15.record(z15.string(),z15.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z15.object({recipientEmail:z15.email().optional(),subject:z15.string().trim().min(1).max(200).default("An update from Fimo"),message:z15.string().trim().min(1).max(5e3),locale:z15.string().trim().min(2).max(20),reason:z15.string().trim().min(1).max(1e3),acknowledgePolicy:z15.literal(!0)})}});import{z as z16}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionListResponseSchema,ProjectVersionResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z16.string(),displayName:z16.string().nullable(),subdomain:z16.string().nullable().optional(),subdomainUpdatedAt:z16.date().nullable().optional(),organizationId:z16.string().nullable(),createdBy:z16.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z16.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z16.string(),thumbnailUrl:z16.string().nullable(),publishedThumbnailUrl:z16.string().nullable(),category:z16.string().nullable(),appUrl:z16.string().nullable(),lastPublishedAt:z16.coerce.date(),styleEditing:z16.boolean().optional()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z16.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z16.object({id:z16.uuid(),name:z16.string(),displayName:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),visibility:ProjectVisibilitySchema,category:z16.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z16.object({id:z16.string(),name:z16.string(),avatar:z16.string().nullable(),color:z16.object({bg:z16.string(),text:z16.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z16.object({path:z16.string(),content:z16.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z16.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z16.object({id:z16.string(),messageId:z16.string(),versionId:z16.string().nullable(),role:ProjectChatMessageRole,parts:z16.array(z16.any()),createdAt:z16.coerce.date()}),MessageUserMetadataSchema=z16.object({id:z16.string(),name:z16.string().nullable().optional(),image:z16.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z16.object({shortTitle:z16.string().optional(),questions:z16.array(z16.object({header:z16.string(),question:z16.string(),answer:z16.string(),selectedLabels:z16.array(z16.string()),freeText:z16.string(),skipped:z16.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z16.number(),metadata:z16.object({user:MessageUserMetadataSchema,changeManifest:z16.array(z16.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z16.object({id:z16.uuid(),versionId:z16.string(),projectId:z16.uuid(),commitHash:z16.string(),name:z16.string(),description:z16.string().nullable(),thumbnailUrl:z16.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z16.object({content:z16.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z16.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z16.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z16.object({success:z16.boolean(),message:z16.string().optional()})),ProjectPublicationStateDTOSchema=z16.object({isPublished:z16.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z16.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z16.object({success:z16.boolean(),message:z16.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z17}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z17.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z17.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z17.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z17.string().nullable(),deletedAt:z17.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z17.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z17.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z17.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z17.object({surface:z17.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z17.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z17.number().int().nonnegative(),conflictCount:z17.number().int().nonnegative()}),EnvDiffResultSchema=z17.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z17.coerce.date(),surfaces:z17.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z18}from"zod";var 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=z18.object({success:z18.literal(!0),downloadUrl:z18.string(),expiresAt:z18.string(),fileSize:z18.number(),duration:z18.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z18.object({success:z18.literal(!0),projectId:z18.string(),projectName:z18.string(),displayName:z18.string(),projectUrl:z18.string(),duration:z18.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z18.object({contentTypes:z18.number(),entries:z18.number(),assets:z18.number(),translations:z18.number(),forms:z18.number(),codeFiles:z18.number(),assetFiles:z18.number()}),ImportPreviewSurfaceDTOSchema=z18.object({name:z18.string(),included:z18.boolean(),count:z18.number().optional(),note:z18.string().optional()}),ImportPreviewDTOSchema=z18.object({projectName:z18.string(),displayName:z18.string().nullable(),visibility:z18.string().nullable(),category:z18.string().nullable(),exportedAt:z18.string(),version:z18.string(),envScope:z18.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z18.array(ImportPreviewSurfaceDTOSchema),fileSize:z18.number(),fileName:z18.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z18.object({success:z18.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z19}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z19.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z19.object({type:z19.literal("manual")}),ScheduleTriggerSchema=z19.object({type:z19.literal("schedule"),cron:z19.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:z19.string().optional()}),WebhookTriggerSchema2=z19.object({type:z19.literal("webhook"),path:z19.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z19.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z20}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z20.object({triggerIndices:z20.array(z20.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z20.object({triggerIndices:z20.array(z20.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z20.object({projectId:z20.uuid(),env:EnvSchema,agentName:z20.string().min(1),triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z20.boolean(),lastFiredAt:z20.coerce.date().nullable(),webhookPath:z20.string().nullable(),createdAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z20.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z20.object({error:z20.literal("webhook_path_taken"),conflictAgent:z20.string(),path:z20.string()}),ManualRunRequestSchema=z20.object({args:z20.unknown().optional(),requestId:z20.string().min(1).max(128).optional()}),DispatchSkippedSchema=z20.object({skipped:z20.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z20.object({sessionId:z20.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z20.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z21}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=z21.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z21.object({token:z21.string().min(1),risk:CapabilityRiskTierSchema,description:z21.string()}),AgentSubAgentSummarySchema=z21.object({name:z21.string().min(1),grant:z21.enum(["inherit","explicit"]),effectiveCaps:z21.array(z21.string().min(1))}),AgentInstallSummaryDTOSchema=z21.object({agentName:z21.string().min(1),env:z21.string().min(1),declaredCapabilities:z21.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z21.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z21.array(CapabilitySummaryEntrySchema),criticalCapabilities:z21.array(CapabilitySummaryEntrySchema),subAgents:z21.array(AgentSubAgentSummarySchema),declaresDelegate:z21.boolean(),cycle:z21.array(z21.string()).nullable(),missingSubAgents:z21.array(z21.string()),warnings:z21.array(z21.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z22}from"zod";var AgentListItemTriggerSchema,AgentListItemActivationSchema,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=z22.object({kind:TriggerKindSchema,summary:z22.string()}),AgentListItemActivationSchema=z22.object({triggerIndex:z22.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z22.string().min(1),active:z22.boolean()}),AgentListItemDTOSchema=z22.object({name:z22.string().min(1),description:z22.string().nullable(),goalFirstLine:z22.string().nullable(),declaredCapabilities:z22.array(CapabilitySummaryEntrySchema),triggers:z22.array(AgentListItemTriggerSchema),activations:z22.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z22.array(AgentListItemDTOSchema))}});import{z as z23}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z23.object({cpuMs:z23.number().nonnegative().default(0),netBytes:z23.number().nonnegative().default(0),walltimeMs:z23.number().nonnegative().default(0),llmTokensIn:z23.number().nonnegative().optional(),llmTokensOut:z23.number().nonnegative().optional()}),AgentSessionDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),env:EnvSchema,agentName:z23.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z23.unknown().optional(),capabilities:z23.array(z23.string()).optional(),dataSources:z23.array(z23.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z23.string().nullable(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),cancelledAt:z23.coerce.date().nullable(),costUsd:z23.number().nonnegative(),costCeilingUsd:z23.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z23.boolean(),lastCheckpointId:z23.uuid().nullable(),branchEnvId:z23.uuid().nullable(),parentSessionId:z23.uuid().nullable(),terminalReason:z23.string().nullable(),errorMessage:z23.string().nullable(),report:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z23.object({id:z23.uuid(),sessionId:z23.uuid(),checkpointIdx:z23.number().int().nonnegative(),payloadRef:z23.string(),payloadSizeBytes:z23.number().int().nonnegative(),checksum:z23.string().length(64),createdAt:z23.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z23.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z23.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z23.object({session:AgentSessionDTOSchema,checkpoints:z23.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z23.object({reason:z23.string().min(1).max(120).optional()})}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z25.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z25.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z25.enum(["secret_text"]),IntegrationCredentialUsageSchema=z25.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z25.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z25.object({mode:IntegrationAuthModeSchema,label:z25.string().min(1),description:z25.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z25.object({id:z25.string().min(1),label:z25.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z25.boolean()}),IntegrationToolDefinitionDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),description:z25.string().min(1)}),IntegrationRecipeDTOSchema=z25.object({title:z25.string().min(1),description:z25.string().min(1),command:z25.string().min(1).optional()}),IntegrationInfoDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z25.array(IntegrationAuthModeDTOSchema),credentials:z25.array(IntegrationCredentialDefinitionDTOSchema),tools:z25.array(IntegrationToolDefinitionDTOSchema),recipes:z25.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),installed:z25.boolean(),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z25.string().nullable(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),installedAt:z25.coerce.date().nullable(),updatedAt:z25.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z25.string(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z25.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z25.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z25.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z25.object({value:z25.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z25.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z25.object({id:z25.uuid(),organizationId:z25.string().min(1),integrationKey:z25.string().min(1),alias:z25.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z25.string().min(1),externalAccountName:z25.string().nullable(),externalBotUserId:z25.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z25.array(z25.string()),connectedAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z25.object({alias:z25.string().min(1).max(120).optional(),token:z25.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z25.object({integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z25.object({ref:z25.string().min(1),connectionAlias:z25.string().min(1).optional(),agentName:z25.string().min(1).max(160).nullable().optional(),force:z25.boolean().optional()}),ProjectChannelBindingDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),connectionId:z25.uuid(),externalWorkspaceId:z25.string().min(1),externalChannelId:z25.string().min(1),externalChannelName:z25.string().nullable(),agentName:z25.string().nullable(),enabled:z25.boolean(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z25.object({markdown:z25.boolean().optional(),summary:z25.boolean().optional(),links:z25.boolean().optional(),images:z25.boolean().optional(),html:z25.union([z25.literal("cleaned"),z25.literal("raw"),z25.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z25.object({url:z25.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z25.object({query:z25.string().min(1),maxResults:z25.number().int().positive().max(20).optional(),sources:z25.array(z25.enum(["web","news","images"])).min(1).max(3).optional(),categories:z25.array(z25.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z25.enum(["hour","day","week","month","year"]).optional(),location:z25.string().min(1).max(160).optional(),country:z25.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z25.object({url:z25.string().url(),search:z25.string().min(1).optional(),limit:z25.number().int().positive().max(200).optional(),includeSubdomains:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z25.object({url:z25.string().url(),limit:z25.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z25.object({text:z25.string().min(1).max(200).optional(),cron:z25.string().min(1).max(120).optional(),timezone:z25.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z25.object({type:z25.enum(["scrape","crawl"]).default("scrape"),urls:z25.array(z25.string().url()).min(1).max(50),scrapeOptions:z25.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z25.object({name:z25.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z25.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z25.string().min(1).max(2e3).optional(),judgeEnabled:z25.boolean().optional(),retentionDays:z25.number().int().min(1).max(365).optional(),notification:z25.object({email:z25.object({enabled:z25.boolean().default(!0),recipients:z25.array(z25.string().email()).min(1).max(20),includeDiffs:z25.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z25.object({monitorId:z25.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z25.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z25.object({connectionAlias:z25.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z25.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.list"),input:z25.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z25.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z25.object({provider:z25.string().min(1),providerCredits:z25.number().nonnegative().optional(),providerCostUsd:z25.number().nonnegative().optional(),requests:z25.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z25.object({credits:z25.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()}),FirecrawlSearchToolOutputSchema=z25.object({query:z25.string(),provider:z25.literal("firecrawl"),warning:z25.string().optional(),results:z25.array(z25.object({title:z25.string(),url:z25.string(),snippet:z25.string().optional(),content:z25.string().optional(),score:z25.number().optional(),publishedAt:z25.string().optional()}))}),FirecrawlMapToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),count:z25.number(),links:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),description:z25.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),total:z25.number(),pages:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()})),warning:z25.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z25.object({cron:z25.string().optional(),text:z25.string().optional(),timezone:z25.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z25.object({id:z25.string().optional(),urls:z25.array(z25.string()).optional(),scrapeOptions:z25.record(z25.string(),z25.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z25.object({id:z25.string(),name:z25.string(),status:z25.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z25.string().nullable().optional(),lastRunAt:z25.string().nullable().optional(),currentCheckId:z25.string().nullable().optional(),targets:z25.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z25.string().nullable().optional(),judgeEnabled:z25.boolean().optional(),estimatedCreditsPerMonth:z25.number().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z25.object({id:z25.string(),monitorId:z25.string(),scheduledFor:z25.string().nullable().optional(),startedAt:z25.string().nullable().optional(),finishedAt:z25.string().nullable().optional(),estimatedCredits:z25.number().optional(),reservedCredits:z25.number().optional(),actualCredits:z25.number().optional(),billingStatus:z25.string().nullable().optional(),summary:z25.object({totalPages:z25.number().optional(),same:z25.number().optional(),changed:z25.number().optional(),new:z25.number().optional(),removed:z25.number().optional(),error:z25.number().optional()}).passthrough().optional(),error:z25.string().nullable().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitors:z25.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),deleted:z25.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),checks:z25.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),check:FirecrawlMonitorCheckOutputSchema,next:z25.string().optional()}),FirecrawlToolKeySchema=z25.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z25.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z25.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z25.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z25.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z25.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z26}from"zod";var ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,ProjectScheduleResponseSchema,ProjectSchedulesListResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_create_dto();init_response();ProjectScheduleStatusSchema=z26.enum(["ok","failed"]),ProjectScheduleDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),env:z26.string().min(1),name:z26.string().min(1),cron:z26.string().min(1),command:z26.string().min(1),enabled:z26.boolean(),lastRunAt:z26.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z26.object({name:z26.string().min(1).max(120),cron:z26.string().min(1).max(120),command:z26.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z26.array(ProjectScheduleDTOSchema))}});import{z as z27}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z27.object({id:z27.uuid(),occurredAt:z27.coerce.date(),projectId:z27.uuid().nullable(),env:z27.string().nullable(),actor:z27.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z27.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z27.unknown().optional(),ipAddress:z27.string().nullable().optional(),userAgent:z27.string().nullable().optional(),error:z27.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z27.object({rows:z27.array(AuditLogRowDTOSchema),nextCursor:z27.string().nullable()})),AuditLogQuerySchema=z27.object({env:z27.string().optional(),action:AuditActionSchema.optional(),actor:z27.string().optional(),from:z27.coerce.date().optional(),to:z27.coerce.date().optional(),limit:z27.coerce.number().int().min(1).max(200).optional(),cursor:z27.string().optional()})}});import{z as z28}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,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,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=z28.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z28.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z28.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z28.object({verb:SurfaceDeltaVerbSchema,key:z28.string(),detail:z28.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z28.record(z28.string(),z28.unknown()).optional()}),PerSurfaceDeltaSchema=z28.object({surface:SurfaceNameSchema,status:z28.enum(["ok","timed_out","failed","unchanged"]),durationMs:z28.number().int().nonnegative().optional(),changedCount:z28.number().int().nonnegative(),conflictCount:z28.number().int().nonnegative(),items:z28.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z28.boolean().optional(),error:z28.string().optional()}),CrossSurfaceFindingSchema=z28.object({id:z28.string(),kind:z28.string(),description:z28.string(),severity:z28.enum(["warning","error"]),source:z28.object({surface:SurfaceNameSchema,key:z28.string()}),target:z28.object({surface:SurfaceNameSchema,key:z28.string()}),actions:z28.array(z28.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z28.object({env:EnvSchema,vs:EnvSchema,syncState:z28.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z28.coerce.date(),surfaces:z28.array(PerSurfaceDeltaSchema),agents:z28.array(z28.object({id:z28.string(),name:z28.string(),status:z28.enum(["active","paused","failed"]),lastRunAt:z28.coerce.date().nullable()})).optional(),crossSurface:z28.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z28.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z28.coerce.date(),surfaces:z28.array(PerSurfaceDeltaSchema),crossSurface:z28.array(CrossSurfaceFindingSchema).optional(),fingerprint:z28.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z28.object({path:z28.string(),state:z28.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z28.string(),additions:z28.number().int().nonnegative(),deletions:z28.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z28.object({oid:z28.string().optional(),content:z28.string().optional(),truncated:z28.boolean(),binary:z28.boolean()}),CodeConflictDetailSchema=z28.object({path:z28.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z28.string(),targetTipSha:z28.string(),mergeBaseSha:z28.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z28.object({id:z28.string(),slug:z28.string(),contentType:z28.string(),data:z28.record(z28.string(),z28.unknown()),updatedAt:z28.coerce.date()}),ContentRowDiffSchema=z28.object({collection:z28.string(),rowId:z28.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z28.object({name:z28.string(),label:z28.string(),isSingleton:z28.boolean(),fields:z28.record(z28.string(),z28.unknown())}),SchemaTypeDiffSchema=z28.object({typeName:z28.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z28.object({id:z28.string(),name:z28.string(),type:z28.enum(["file","folder"]),mimeType:z28.string().nullable(),storageKey:z28.string().nullable(),url:z28.string().nullable(),fileSize:z28.number().nullable(),width:z28.number().nullable(),height:z28.number().nullable(),altText:z28.string().nullable(),caption:z28.string().nullable(),createdAt:z28.coerce.date(),updatedAt:z28.coerce.date()}),AssetDiffSchema=z28.object({assetId:z28.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z28.object({locale:z28.string(),key:z28.string(),parent:z28.string().nullable(),child:z28.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z28.object({formName:z28.string(),label:z28.string().nullable(),schemaFingerprint:z28.string(),fields:z28.record(z28.string(),z28.unknown()),settings:z28.record(z28.string(),z28.unknown()).optional()}),FormSchemaDiffSchema=z28.object({formName:z28.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z28.object({agentName:z28.string(),triggerIndex:z28.number().int().nonnegative(),triggerKind:z28.string(),triggerSpec:z28.record(z28.string(),z28.unknown()),enabled:z28.boolean(),emailRecipients:z28.array(z28.string()).nullable(),qstashScheduleId:z28.string().nullable()}),ActivationDiffSchema=z28.object({agentName:z28.string(),triggerIndex:z28.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),ConflictSchema=z28.object({surface:SurfaceNameSchema,key:z28.string(),kind:z28.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity"]).optional(),description:z28.string(),parentValue:z28.unknown().optional(),childValue:z28.unknown().optional(),conflictingFields:z28.array(z28.string()).optional(),code:z28.object({path:z28.string(),unresolvable:z28.boolean().optional(),reason:z28.string().optional()}).optional()}),FieldPickSchema=z28.object({field:z28.string(),choice:z28.enum(["parent","child","pick","ai-pick"]),pickedValue:z28.unknown().optional(),aiSessionId:z28.string().optional()}),ConflictResolutionSchema=z28.object({surface:SurfaceNameSchema,key:z28.string(),choice:z28.enum(["parent","child","pick"]),pickedValue:z28.unknown().optional(),fieldPicks:z28.array(FieldPickSchema).optional()}),MergeResultSchema=z28.object({ok:z28.boolean(),mergeId:z28.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z28.array(z28.object({surface:SurfaceNameSchema,count:z28.number().int().nonnegative()})),conflicts:z28.array(ConflictSchema).optional(),summary:z28.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z28.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z28.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z28.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z28.boolean().optional()}),ResolvedStrategySchema=z28.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z28.boolean()}),MergeRequestSchema=z28.object({from:EnvSchema,allowDirectMerge:z28.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z28.object({mergeId:z28.string().uuid(),streamUrl:z28.string(),strategy:ResolvedStrategySchema,acceptedAt:z28.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z28.object({mergeId:z28.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z28.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z28.array(ConflictSchema),draftResolutions:z28.array(ConflictResolutionSchema),lastEditedBy:z28.string().nullable(),lastEditedAt:z28.coerce.date().nullable(),initiator:z28.object({userId:z28.string().nullable(),role:z28.string().nullable(),agentName:z28.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z28.object({resolutions:z28.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z28.object({mergeId:z28.string().uuid(),draftResolutions:z28.array(ConflictResolutionSchema),lastEditedAt:z28.coerce.date(),lastEditedBy:z28.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z28.object({mergeId:z28.string().uuid(),resolutions:z28.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z28.object({mergeId:z28.string().uuid()}),PublishReleaseRequestSchema=z28.object({version:z28.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z28.string().max(2e4).optional()}),PublishReleaseResultSchema=z28.object({releaseTag:z28.string(),sha:z28.string(),publishedAt:z28.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z29}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z29.object({surface:SurfaceNameSchema,key:z29.string(),label:z29.string()}),InlineSchema=z29.object({text:z29.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z29.discriminatedUnion("type",[z29.object({type:z29.literal("paragraph"),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("preview"),ref:DiffRefSchema,caption:z29.string().optional()}),z29.object({type:z29.literal("code"),code:z29.string(),lang:z29.string().optional(),caption:z29.string().optional()}),z29.object({type:z29.literal("risk"),level:z29.enum(["warning","error"]),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("list"),items:z29.array(z29.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z29.object({headline:z29.string(),blocks:z29.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z29.object({summary:EnvDiffSummarySchema,fingerprint:z29.string(),generatedAt:z29.coerce.date(),cached:z29.boolean().optional(),credits:z29.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z30}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z30.object({date:z30.string(),visitors:z30.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z30.object({key:z30.string(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z30.object({path:z30.string(),pageName:z30.string().nullable().optional(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z30.object({preset:z30.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z30.string(),requestedTo:z30.string(),effectiveFrom:z30.string(),effectiveTo:z30.string(),isRetentionLimited:z30.boolean(),groupBy:z30.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z30.object({date:z30.string(),content:z30.string(),updatedAt:z30.string(),updatedByUserId:z30.string()}),ProjectPageviewAnalyticsDTOSchema=z30.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative(),bounceRate:z30.number().min(0).max(100),viewsPerVisit:z30.number().nonnegative(),averageVisitDurationSeconds:z30.number().nonnegative(),visitorsSeries:z30.array(ProjectDailyVisitorsDTOSchema),topPages:z30.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z30.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z31}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z31.object({id:z31.string(),email:z31.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z31.coerce.date(),createdAt:z31.coerce.date(),inviterUserId:z31.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z31.object({id:z31.string(),token:z31.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z31.object({success:z31.boolean(),projectId:z31.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z32}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z32.object({id:z32.string(),name:z32.string(),image:z32.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z32.object({count:z32.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z32.object({counts:z32.object({signed_up:z32.int(),activated:z32.int()}),credits:z32.object({total:z32.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z32.email(),emailVerified:z32.boolean(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z33}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z33.object({id:z33.string(),principalType:ProjectPrincipalTypeSchema,principalId:z33.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z33.coerce.date(),expiresAt:z33.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z33.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z33.record(z33.string(),z33.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z33.object({access:z33.array(ProjectAccessItemDTOSchema),invites:z33.array(ProjectInviteDTOSchema),organization:z33.object({name:z33.string().nullable(),logo:z33.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z33.object({success:z33.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z33.object({success:z33.boolean(),projectId:z33.uuid()}))}});import{z as z34}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z34.object({publicationStatus:PublicationStatusSchema,appUrl:z34.string().nullable(),lastPublishedAt:z34.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z35}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewBootstrapDTOSchema,PreviewBootstrapDTO,PreviewBootstrapResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z35.object({url:z35.url(),expiresAt:z35.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z35.discriminatedUnion("source",[z35.object({source:z35.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z35.null()}),z35.object({source:z35.literal("dev"),artifact:z35.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z36}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z36.string(),slug:z36.string().nullable(),logo:z36.string().nullable(),metadata:z36.record(z36.string(),z36.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z36.object({id:z36.string(),name:z36.string(),email:z36.email(),image:z36.string().nullable()}),OrganizationMemberDTOSchema=z36.object({id:z36.string(),userId:z36.string(),organizationId:z36.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z36.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z37}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z37.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z37.object({reason:CancellationReasonCodeSchema,details:z37.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z37.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z37.object({included:z37.number().optional(),unitPrice:z37.number().optional(),dailyCap:z37.number().nullable().optional()}),EntitlementsDTOSchema=z37.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z37.object({retentionDays:z37.number().int().positive(),canUseExtendedDateRanges:z37.boolean()}).optional(),members:z37.object({canInvite:z37.boolean(),maxMembers:z37.number().int().positive().nullable()}).optional(),projects:z37.object({canCreatePrivateProjects:z37.boolean(),maxPrivateProjects:z37.number().int().positive().nullable()}).optional(),domains:z37.object({canUseCustomDomains:z37.boolean(),maxDomains:z37.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z37.object({id:z37.string(),external_id:z37.string(),customerId:z37.string(),planId:z37.string(),planCode:TemplateCodeSchema,currentPeriod:z37.object({start:z37.string(),end:z37.string().nullable()}),cancelAt:z37.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z37.string(),nextPaymentAt:z37.string().nullable(),baseAmount:z37.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z37.object({totalCap:z37.number(),dailyCap:z37.number(),usedTotal:z37.number()}),CreditBalanceDTOSchema=z37.object({total:z37.number(),base:z37.number(),dailyBase:z37.number(),purchases:z37.number(),awards:z37.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z37.object({total:z37.number(),nearLimit:z37.boolean(),canChat:z37.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z37.object({dailyFreeAvailable:z37.number(),monthlyAvailable:z37.number(),purchasedAvailable:z37.number(),awardedAvailable:z37.number()}),ProjectDailyCreditAllowanceDTOSchema=z37.object({periodCap:z37.number(),dailyGrant:z37.number(),usedThisPeriod:z37.number(),remainingThisPeriod:z37.number()}),ProjectCreditBalanceDTOSchema=z37.object({projectId:z37.uuid(),organizationId:z37.string(),balance:z37.object({totalAvailable:z37.number(),nearLimit:z37.boolean(),canUseAi:z37.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z37.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z37.object({invoiceId:z37.string(),newBalance:z37.int(),creditCount:z37.int(),amountUsd:z37.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z37.object({url:z37.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z38}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z38.object({brand:z38.string(),last4:z38.string(),exp:z38.string(),isDefault:z38.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z39}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z39.string().superRefine((path64,ctx)=>{let segments=path64.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z39.object({type:z39.literal("renameField"),contentType:z39.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z39.object({enabled:z39.boolean()}).strict(),ContentTypeDTOSchema=z39.object({id:z39.string(),name:z39.string(),label:z39.string(),isSingleton:z39.boolean(),i18n:ContentTypeI18nSchema,fields:z39.record(z39.string(),FieldDefinitionSchema),createdAt:z39.string(),updatedAt:z39.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z39.object({contentTypes:z39.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z39.object({id:z39.string(),entryId:z39.string(),documentId:z39.string(),slug:z39.string(),locale:z39.string().optional(),createdAt:z39.string(),updatedAt:z39.string(),__fimo:z39.object({contentType:z39.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({limit:z39.number(),offset:z39.number(),total:z39.number(),hasMore:z39.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z39.object({contentType:z39.string(),count:z39.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z39.object({counts:z39.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z39.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z39.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z39.union([z39.string(),z39.number(),z39.boolean(),z39.null()]),entryWhereOperatorSchema=z39.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z39.array(entryWhereScalarSchema).optional(),$nin:z39.array(entryWhereScalarSchema).optional(),$contains:z39.string().optional(),$startsWith:z39.string().optional(),$null:z39.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z39.object({data:z39.record(z39.string(),z39.unknown()),locale:z39.string().min(1).optional(),documentId:z39.uuid().optional()}),entryIdsSchema=z39.array(z39.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z39.object({sql:z39.string().min(1)}),BulkCreateEntriesRequestSchema=z39.object({entries:z39.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z39.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z39.object({updates:z39.array(z39.object({id:z39.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,locale:z39.string().min(1).optional()}),z39.object({where:EntryWhereSchema,locale:z39.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z39.object({data:z39.array(z39.record(z39.string(),z39.unknown())),meta:z39.object({rowCount:z39.number().int().nonnegative(),truncated:z39.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({created:z39.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({updated:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({deleted:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z40}from"zod";var 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=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z40.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z40.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z40.object({field:CmsFieldNameSchema,direction:z40.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z40.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z40.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z40.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z40.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z40.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z41}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=z41.object({id:z41.string(),name:z41.string()}),AssetDTOSchema=z41.object({id:z41.string(),name:z41.string(),type:AssetTypeSchema,originalFileName:z41.string().nullable(),parentId:z41.string().nullable(),mimeType:z41.string().nullable(),fileSize:z41.number().nullable(),url:z41.string().nullable(),storageKey:z41.string().nullable(),createdAt:z41.string(),updatedAt:z41.string(),altText:z41.string().nullable().optional(),caption:z41.string().nullable().optional(),aiCaption:z41.string().nullable().optional(),aiAltText:z41.string().nullable().optional(),aiTags:z41.array(z41.string()).nullable().optional(),aiPrimaryColor:z41.string().nullable().optional(),aiProcessingStatus:z41.string().nullable().optional(),width:z41.number().nullable().optional(),height:z41.number().nullable().optional(),path:z41.array(AssetPathItemSchema).optional(),hasChildren:z41.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z41.lazy(()=>z41.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z41.array(AssetDTOSchema))}});import{z as z42}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z42.object({key:z42.string(),value:z42.string().optional(),defaultValue:z42.string(),locale:z42.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z43}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=z43.object({id:z43.string(),name:z43.string(),type:z43.enum(["file","folder"]),path:z43.string(),children:z43.lazy(()=>z43.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z43.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z43.object({path:z43.string(),exists:z43.boolean(),type:z43.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z44}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z44.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z44.object({items:z44.array(ProjectMessagePublicDTOSchema),nextCursor:z44.string().nullable()}),ChatDeletionDTOSchema=z44.object({success:z44.boolean(),deletedCount:z44.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z45}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=z45.object({url:z45.string().url(),key:z45.string(),size:z45.number(),contentType:z45.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z46}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=z46.object({canAccess:z46.boolean(),permissions:z46.record(z46.string(),z46.boolean()),role:z46.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z47}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:z47.string().trim().default(""),sort:z47.enum(["recent","name","relevance"]).default("recent"),category:z47.string().optional(),visibility:z47.enum(["public","private"]).optional()})}});import{z as z48}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=z48.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z48.enum(["fimo","external"]),PaymentStatusSchema=z48.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z48.object({id:z48.string().uuid(),domain:z48.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z48.boolean(),price:z48.number().int().nullable(),renewalPrice:z48.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z48.string().nullable(),failureReason:z48.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z48.object({domain:z48.string(),available:z48.boolean(),premium:z48.boolean(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),purchaseType:z48.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z48.object({domain:z48.string(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),premium:z48.boolean(),allowedYears:z48.array(z48.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z48.object({firstName:z48.string().max(100),lastName:z48.string().max(100),companyName:z48.string().max(100).optional(),address1:z48.string().max(255),address2:z48.string().max(255).optional(),city:z48.string().max(100),state:z48.string().max(100),zip:z48.string().max(20),country:z48.string().max(2),phone:z48.string().max(30),email:z48.union([z48.string().email().max(255),z48.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z48.object({firstName:z48.string().min(1).max(100),lastName:z48.string().min(1).max(100),companyName:z48.string().max(100).optional(),address1:z48.string().min(1).max(255),address2:z48.string().max(255).optional(),city:z48.string().min(1).max(100),state:z48.string().min(1).max(100),zip:z48.string().min(1).max(20),country:z48.string().min(1).max(2),phone:z48.string().min(1).max(30),email:z48.string().email().max(255)}),SearchDomainsRequestSchema=z48.object({keyword:z48.string().min(1).max(100),tldFilter:z48.array(z48.string()).optional()}),CheckAvailabilityRequestSchema=z48.object({domains:z48.array(z48.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=z48.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z48.object({domain:DomainNameSchema,years:z48.number().int().min(1).max(10).optional().default(3),autoRenew:z48.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z48.object({autoRenew:z48.boolean().optional()}),RenewDomainRequestSchema=z48.object({years:z48.number().int().min(1).max(10).optional().default(1),autoRenew:z48.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z48.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z48.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z48.object({verified:z48.boolean(),email:z48.string().nullable(),verifyBy:z48.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z49}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=z49.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=z49.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=z49.object({txtName:z49.string().nullable().optional(),txtValue:z49.string().nullable().optional(),httpUrl:z49.string().nullable().optional(),httpBody:z49.string().nullable().optional(),cname:z49.string().nullable().optional(),cnameTarget:z49.string().nullable().optional()}),SSLValidationErrorSchema=z49.object({message:z49.string()}),OwnershipVerificationSchema=z49.object({type:z49.string(),name:z49.string(),value:z49.string()}),ProjectDomainSSLDTOSchema=z49.object({status:z49.string(),method:z49.string().nullable(),type:z49.string().nullable(),validationRecords:z49.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z49.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z49.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z49.enum(["subdomain","apex"]),RedirectConfigSchema=z49.object({type:z49.literal("apex_to_www"),linkedDomainId:z49.string()}).nullable().optional(),ProjectDomainDTOSchema=z49.object({id:z49.string(),hostname:z49.string(),status:z49.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z49.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z49.string(),scdCnameTarget:z49.string().optional(),apexTargets:z49.array(z49.string()),dnsAutoConfigured:z49.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z49.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z49.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z49.object({hostname:z49.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:z49.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z49.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z49.object({success:z49.boolean(),hostname:z49.string()}))}});import{z as z50}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=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z50.object({available:z50.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z50.object({slug:z50.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z50.object({subdomain:z50.string(),subdomainUpdatedAt:z50.coerce.date()})),SubdomainSuggestionsQuerySchema=z50.object({base:z50.string().max(100).optional(),max:z50.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z50.object({suggestions:z50.array(z50.string())}))}});import{z as z51}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=z51.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z51.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=z51.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z51.number(),credits:z51.number().optional(),billingMode:z51.enum(["fimo-credits","provider-account"]).optional(),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z52}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=z52.object({options:z52.record(z52.string(),z52.unknown()),name:z52.string().optional(),parentId:z52.string().nullable().optional(),altText:z52.string().optional(),caption:z52.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z52.string().min(1).optional(),model:z52.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=z52.object({jobId:z52.string(),status:z52.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z52.string().nullable().optional(),credits:z52.number().optional(),costUsd:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z52.object({error:z52.string(),code:z52.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:z52.array(GenerationTaskIdSchema).optional(),availableModels:z52.array(z52.string()).optional(),issues:z52.array(z52.unknown()).optional()})}});import{z as z53}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=z53.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z53.object({name:z53.string(),key:z53.string(),description:z53.string(),type:FlagTypeSchema,required:z53.boolean(),defaultValue:z53.unknown().optional(),enumValues:z53.array(z53.string()).optional(),isArray:z53.boolean()}),AssetModelPriceSchema=z53.object({unitPrice:z53.number(),unit:z53.string(),confidence:z53.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z53.object({id:z53.string(),shortName:z53.string(),provider:z53.string(),source:z53.string(),modality:z53.enum(["image","video","audio"]),tags:z53.array(z53.string()),displayName:z53.string(),description:z53.string(),flags:z53.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z53.object({model:z53.string(),costUsd:z53.number(),credits:z53.number(),billingMode:z53.enum(["fimo-credits","provider-account"]),confidence:z53.enum(["exact","estimated","metered"]),basis:z53.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z54}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=z54.object({tourId:z54.string(),version:z54.string(),status:z54.string(),completedAt:z54.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z54.array(UserTourDTOSchema))}});import{z as z55}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=z55.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z55.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z55.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z55.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z55.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z55.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z55.enum(["user","agent","system"]),SupportReportTagSchema=z55.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z55.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z55.object({organization:z55.object({id:z55.string().trim().min(1).max(255),name:z55.string().trim().max(240).optional()}),project:z55.object({id:z55.uuid(),name:z55.string().trim().max(240).optional(),createdAt:z55.coerce.date().optional()}).optional(),environment:z55.string().trim().max(255).optional(),clientVersion:z55.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z55.object({message:z55.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z55.string().trim().max(200).optional(),limit:z55.coerce.number().int().min(1).max(100).default(50),offset:z55.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z55.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z55.uuid().nullable().optional(),note:z55.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=z55.object({message:z55.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z55.object({kind:SupportReportLinkKindSchema,label:z55.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z55.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z55.object({kind:SupportReportActorKindSchema,id:z55.string().nullable(),name:z55.string().nullable()}),SupportReportLinkDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportLinkKindSchema,label:z55.string(),url:SupportReportHttpUrlSchema,externalId:z55.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportEventKindSchema,body:z55.string().nullable(),metadata:z55.record(z55.string(),z55.unknown()),actor:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z55.object({id:z55.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z55.array(z55.string()),source:SupportReportSourceSchema,message:z55.string(),reporter:z55.object({id:z55.string().nullable(),name:z55.string().nullable(),email:z55.string().nullable()}),organization:z55.object({id:z55.string().nullable(),name:z55.string()}),project:z55.object({id:z55.uuid().nullable(),name:z55.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z55.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z55.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z55.string().nullable(),deliveredAt:z55.coerce.date().nullable()}).nullable(),duplicateOfReportId:z55.uuid().nullable(),resolvedAt:z55.coerce.date().nullable(),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z55.string().nullable(),clientVersion:z55.string().nullable(),links:z55.array(SupportReportLinkDTOSchema),events:z55.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z55.object({reports:z55.array(SupportReportSummaryDTOSchema),total:z55.number().int().nonnegative(),statusCounts:z55.object({new:z55.number().int().nonnegative(),in_progress:z55.number().int().nonnegative(),waiting:z55.number().int().nonnegative(),resolved:z55.number().int().nonnegative(),duplicate:z55.number().int().nonnegative(),irrelevant:z55.number().int().nonnegative(),ignored:z55.number().int().nonnegative()}),limit:z55.number().int().positive(),offset:z55.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z55.object({id:z55.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z55.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z56}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=z56.iso.datetime({offset:!0}).pipe(z56.coerce.date()),OpsRecentChatInputSchema=z56.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z56.string().trim().min(1).max(255).optional(),limit:z56.coerce.number().int().min(1).max(200).default(100),cursor:z56.string().trim().min(1).max(2e3).optional(),slim:z56.boolean().default(!0),reason:z56.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=z56.object({id:z56.string(),messageId:z56.string(),env:z56.string(),versionId:z56.string().nullable(),userId:z56.string().nullable(),role:z56.string(),parts:z56.array(z56.record(z56.string(),z56.unknown())),metadata:z56.object({status:z56.string().optional(),traceUrl:z56.string().optional(),externalFileChanges:z56.array(z56.unknown()).optional()}),stats:z56.object({toolCount:z56.number().int().nonnegative(),failedToolCount:z56.number().int().nonnegative()}),createdAt:z56.iso.datetime({offset:!0}),project:z56.object({id:z56.string(),name:z56.string(),displayName:z56.string().nullable(),organizationId:z56.string().nullable()})}),OpsRecentChatResponseSchema=z56.object({target:z56.object({backendProfile:OpsBackendProfileSchema,projectEnv:z56.string().nullable()}),window:z56.object({from:z56.iso.datetime({offset:!0}),to:z56.iso.datetime({offset:!0})}),messages:z56.object({items:z56.array(OpsRecentChatMessageSchema),nextCursor:z56.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z57}from"zod";function createAgentRunWebhookEventDataSchema(status){return z57.object({run:z57.object({id:z57.string(),agentName:z57.string(),trigger:z57.string(),status:z57.literal(status),startedAt:z57.string().nullable(),finishedAt:z57.string().nullable(),reason:z57.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,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_create_dto();init_response();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"],WebhookEventTypeSchema=z57.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z57.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z57.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z57.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z57.union([z57.literal(0),z57.literal(5),z57.literal(30),z57.literal(60)]),EntryChangedWebhookEventDataSchema=z57.object({reason:WebhookEntryChangeReasonSchema,operationId:z57.string().optional(),batch:z57.object({index:z57.number().int().positive(),total:z57.number().int().positive()}).optional(),changes:z57.array(z57.object({action:WebhookEntryChangeActionSchema,contentType:z57.string(),id:z57.string(),documentId:z57.string(),locale:z57.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z57.object({form:z57.object({id:z57.string(),label:z57.string()}),submission:z57.object({id:z57.string(),data:z57.record(z57.string(),z57.unknown()),submittedAt:z57.string()})}),PublishStartedWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("publishing"),startedAt:z57.string()})}),PublishSucceededWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("published"),url:z57.string(),publishedAt:z57.string(),firstPublish:z57.boolean()})}),PublishFailedWebhookEventDataSchema=z57.object({publication:z57.object({status:z57.literal("failed"),reason:z57.string()})}),PublishUnpublishedWebhookEventDataSchema=z57.object({publication:z57.object({previousUrl:z57.string(),unpublishedAt:z57.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z57.object({review:z57.object({id:z57.string(),runId:z57.string(),agentName:z57.string(),classification:z57.string(),summary:z57.string(),reasons:z57.array(z57.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z57.object({review:z57.object({id:z57.string(),runId:z57.string(),agentName:z57.string(),resolution:z57.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z57.object({report:z57.object({weekStart:z57.string(),weekEnd:z57.string(),pageviews:z57.number(),visitors:z57.number(),previousPageviews:z57.number(),previousVisitors:z57.number()})}),MediaAssetWebhookEventDataSchema=z57.object({id:z57.string().nullable(),name:z57.string().nullable(),type:z57.string(),mimeType:z57.string().nullable(),fileSize:z57.number().nullable()}),MediaUploadedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.enum(["updated","moved","analysis"]),analysis:z57.object({category:z57.string(),status:z57.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.literal("generated"),generation:z57.object({model:z57.string(),mode:z57.string()})}),MediaProcessingFailedWebhookEventDataSchema=z57.object({asset:MediaAssetWebhookEventDataSchema,operation:z57.enum(["analysis","generation"]),failure:z57.object({code:z57.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},WebhookEventFamilySchema=z57.enum(["entries","forms","publish","agents","analytics","media"]),WebhookDestinationKindSchema=z57.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z57.discriminatedUnion("source",[z57.object({source:z57.literal("literal"),value:z57.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z57.object({source:z57.literal("secret"),key:z57.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z57.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z57.object({name:z57.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z57.object({name:z57.string(),source:z57.enum(["literal","secret"]),secretKey:z57.string().nullable(),secretPrefix:z57.string().nullable(),configured:z57.literal(!0)}),WebhookFilterSchema=z57.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z57.string().min(1).max(255).optional(),agentName:z57.string().min(1).max(120).optional(),mediaType:z57.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z57.string().min(1).max(255).optional(),locale:z57.string().min(1).max(120).optional()}),JsonValueSchema=z57.lazy(()=>z57.union([z57.string(),z57.number(),z57.boolean(),z57.null(),z57.array(JsonValueSchema),z57.record(z57.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z57.object({name:z57.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z57.url(),enabled:z57.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z57.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z57.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z57.object({name:z57.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z57.url().optional(),enabled:z57.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z57.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z57.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z57.object({eventType:WebhookEventTypeSchema.optional(),data:z57.record(z57.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z57.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z57.uuid(),name:z57.string(),eventType:WebhookEventTypeSchema,enabled:z57.boolean(),destination:z57.object({host:z57.string(),maskedUrl:z57.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z57.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z57.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z57.coerce.date().nullable(),deliveryStats24h:z57.object({succeeded:z57.number().int().nonnegative(),failed:z57.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z57.uuid(),projectId:z57.uuid(),env:EnvSchema,eventId:z57.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z57.number().int().positive(),test:z57.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z57.number().int().nonnegative(),responseStatus:z57.number().int().nullable(),lastErrorCode:z57.string().nullable(),lastErrorMessage:z57.string().nullable(),payloadAvailable:z57.boolean(),destination:z57.object({host:z57.string(),maskedUrl:z57.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z57.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z57.string().nullable(),qstashMessageId:z57.string().nullable(),deliveredAt:z57.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z57.object({items:z57.array(WebhookDeliveryDTOSchema),pagination:z57.object({page:z57.number().int().positive(),limit:z57.number().int().positive(),total:z57.number().int().nonnegative(),totalPages:z57.number().int().positive(),hasMore:z57.boolean()}),stats:z57.object({total:z57.number().int().nonnegative(),succeeded:z57.number().int().nonnegative(),failed:z57.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z57.object({id:z57.uuid(),deliveryId:z57.uuid(),attempt:z57.number().int().positive(),status:z57.enum(["delivering","succeeded","failed"]),responseStatus:z57.number().int().nullable(),durationMs:z57.number().int().nonnegative(),responseExcerpt:z57.string().nullable(),errorCode:z57.string().nullable(),errorMessage:z57.string().nullable(),createdAt:z57.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z57.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z57.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z58}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=z58.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z58.object({total:z58.number(),base:z58.number(),purchases:z58.number(),awards:z58.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z58.object({id:z58.string(),name:z58.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z58.object({type:z58.string(),brand:z58.string().nullable(),last4:z58.string().nullable(),expirationDate:z58.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z58.object({currency:z58.string(),nextPaymentAmount:z58.number().nullable(),nextPaymentAt:z58.string().nullable(),billingInterval:z58.string().nullable(),totalAmount:z58.number().nullable(),discountAmount:z58.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z58.object({id:z58.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z58.string().nullable(),currentPeriodEndsAt:z58.string().nullable(),renewsAt:z58.string().nullable(),cancelAt:z58.string().nullable(),renewAutomatically:z58.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z58.object({type:z58.enum(["low_balance","critical_balance","approaching_limit"]),message:z58.string(),estimatedPromptsRemaining:z58.number().nullable(),avgCostPerPrompt:z58.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z58.object({monthlyCredits:z58.number().nullable(),usedThisPeriod:z58.number(),remainingThisPeriod:z58.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z58.object({organizationId:z58.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z58.string().nullable(),tenureDays:z58.number().int().nonnegative(),capturedAt:z58.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z58.object({hasSubscription:z58.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z58.number().nullable(),alerts:z58.array(CreditAlertDTOSchema),portalUrl:z58.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z58.object({creditCount:z58.number().int().positive(),expiresAt:z58.string().datetime().nullable().optional(),message:z58.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z58.literal("free"),amountCents:z58.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z58.literal("purchase"),amountCents:z58.number().int().positive()}),CreditTopupRequestDTOSchema=z58.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z58.object({success:z58.boolean(),transactionId:z58.string().nullable(),newBalance:z58.number(),creditCount:z58.number(),type:z58.enum(["free","purchase"]),invoiceId:z58.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z59}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=z59.object({totalCredits:z59.number(),totalCostUsd:z59.number(),totalMessages:z59.number(),avgCostPerMessage:z59.number(),periodStart:z59.string().nullable(),periodEnd:z59.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().email().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z59.object({date:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().email().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z59.array(UsageByUserForProjectDTOSchema),timeline:z59.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z59.object({summary:UsageSummaryDTOSchema,byProject:z59.array(UsageByProjectDTOSchema),byUser:z59.array(UsageByUserDTOSchema),timeline:z59.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z60}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=z60.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z60.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z60.object({startDate:z60.string().optional(),endDate:z60.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z60.coerce.number().int().positive().default(1),limit:z60.coerce.number().int().positive().max(100).default(20),sortBy:z60.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z60.string().optional()}),UsageOverviewSummaryDTOSchema=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),avgCreditsPerMessage:z60.number(),periodStart:z60.string(),periodEnd:z60.string(),creditsChange:z60.number().nullable(),costChange:z60.number().nullable(),messagesChange:z60.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z60.object({organizationId:z60.string(),organizationName:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),userCount:z60.number(),projectCount:z60.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().nullable(),userImage:z60.string().nullable(),organizationId:z60.string().nullable(),organizationName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),projectCount:z60.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),organizationId:z60.string(),organizationName:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),userCount:z60.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z60.object({id:z60.string(),name:z60.string(),value:z60.number(),percentage:z60.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z60.object({day:z60.number(),hour:z60.number(),value:z60.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z60.object({summary:UsageOverviewSummaryDTOSchema,timeline:z60.array(UsageTimelinePointDTOSchema),topOrganizations:z60.array(OrganizationUsageRowDTOSchema),topUsers:z60.array(UserUsageRowDTOSchema),topProjects:z60.array(ProjectUsageRowDTOSchema),creditDistribution:z60.array(UsageDistributionItemDTOSchema),heatmap:z60.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z60.object({page:z60.number(),limit:z60.number(),totalItems:z60.number(),totalPages:z60.number(),hasMore:z60.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z60.object({organizations:z60.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z60.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z60.object({users:z60.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z60.string(),ownerName:z60.string().nullable(),ownerEmail:z60.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z60.object({projects:z60.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z60.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z60.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z60.object({credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z60.object({id:z60.string(),name:z60.string(),createdAt:z60.string(),memberCount:z60.number(),projectCount:z60.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z60.object({id:z60.string(),name:z60.string().nullable(),email:z60.string(),image:z60.string().nullable(),createdAt:z60.string(),organizationCount:z60.number(),projectCount:z60.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z60.object({id:z60.string(),name:z60.string(),displayName:z60.string().nullable(),createdAt:z60.string(),organizationId:z60.string(),organizationName:z60.string(),ownerId:z60.string(),ownerName:z60.string().nullable(),ownerEmail:z60.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z61}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=z61.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z61.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z61.object({command:z61.string().min(1).max(1e4),cwd:z61.string().optional(),projectEnv:EnvSchema.optional(),env:z61.record(z61.string(),z61.string()).optional(),name:z61.string().optional(),waitForCompletion:z61.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z61.object({identifier:z61.string(),status:SandboxProcessStatusSchema,command:z61.string().optional(),startedAt:z61.string().optional(),exitCode:z61.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z61.object({processes:z61.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z61.object({processId:z61.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z61.object({success:z61.boolean(),message:z61.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z62}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_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_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit2(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit2(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit2(["status","--porcelain"],cwd)).length>0}async function cloneRepo2(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit2(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit2(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit2,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo2,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});var project_context_exports={};__export(project_context_exports,{EnvNotFoundError:()=>EnvNotFoundError,GitBranchUndetectedError:()=>GitBranchUndetectedError,InvalidEnvOverrideError:()=>InvalidEnvOverrideError,NotInProjectError:()=>NotInProjectError,bootstrapProjectCommand:()=>bootstrapProjectCommand,envOverrideFromCommand:()=>envOverrideFromCommand,envSourceBanner:()=>envSourceBanner,getProjectContext:()=>getProjectContext,projectConfig:()=>projectConfig});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveEnvFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{env:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||branch==="HEAD"||!isValidEnv(branch)?null:{env:branch,source:"branch"}}catch{return null}}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let env,source,readOnly=!1;if(opts.envOverride!==void 0){if(!isValidEnv(opts.envOverride))throw new InvalidEnvOverrideError(opts.envOverride);env=opts.envOverride,source="flag"}else{let fromGit=await resolveEnvFromGit(cwd);if(fromGit)env=fromGit.env,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{if(opts.requireBranch)throw await isGitRepo(cwd)?new GitBranchUndetectedError:new NotInProjectError;env=DEFAULT_ENV,source="fallback"}}if(opts.api&&env!=="prod")try{let names=(await opts.api.listEnvs(settings.projectId)).map(e=>e.env);if(!names.includes(env)&&source==="flag")throw new EnvNotFoundError(env,names)}catch(err){if(err instanceof EnvNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,env,source,readOnly:readOnly||void 0}}function envSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--env":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"default",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 env: ${ctx.env} (from ${sourceHint}${ro})`}function envOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let env=cur.opts().env;if(typeof env=="string"&&env.length>0)return env;cur=cur.parent??null}}function projectConfig(ctx){return configForApiUrl(ctx.apiUrl)}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let envOverride2=envOverrideFromCommand(cmd),baseApi=new FimoApiClient(loadConfig()),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,requireBranch:bootstrapOpts.requireBranch,api:baseApi}),cfg=configForApiUrl(ctx.apiUrl),projectApi=ctx.apiUrl&&ctx.apiUrl!==loadConfig().apiUrl?new FimoApiClient(cfg):baseApi;if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
437
437
  `)}if(bootstrapOpts.refuseReadOnly&&ctx.readOnly)throw new Error(`Refusing to run a mutating command against read-only env '${ctx.env}'. Switch off the release/* tag or pass --env <writable-env>.`);return{ctx,cfg,api:projectApi.withEnv(ctx.env)}}var NotInProjectError,InvalidEnvOverrideError,EnvNotFoundError,GitBranchUndetectedError,init_project_context=__esm({"src/cli/utils/project-context.ts"(){init_esm();init_api();init_config();init_git();init_project();NotInProjectError=class extends Error{static{__name(this,"NotInProjectError")}constructor(){super("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project."),this.name="NotInProjectError"}};__name(projectSettingsFromEnv,"projectSettingsFromEnv");InvalidEnvOverrideError=class extends Error{static{__name(this,"InvalidEnvOverrideError")}value;constructor(value){super(`--env value '${value}' is invalid. Env names must match /^[a-zA-Z0-9._/-]+$/, not start with '-', and be \u2264255 chars.`),this.name="InvalidEnvOverrideError",this.value=value}},EnvNotFoundError=class extends Error{static{__name(this,"EnvNotFoundError")}env;knownEnvs;constructor(env,knownEnvs){super(`Env '${env}' not found on the server. Known envs: ${knownEnvs.length>0?knownEnvs.join(", "):"(none yet)"}.`),this.name="EnvNotFoundError",this.env=env,this.knownEnvs=knownEnvs}},GitBranchUndetectedError=class extends Error{static{__name(this,"GitBranchUndetectedError")}constructor(){super("In a git repository but no branch could be detected (detached HEAD or empty repo). Pass --env <name> to target an env explicitly."),this.name="GitBranchUndetectedError"}};__name(resolveEnvFromGit,"resolveEnvFromGit");__name(getProjectContext,"getProjectContext");__name(envSourceBanner,"envSourceBanner");__name(envOverrideFromCommand,"envOverrideFromCommand");__name(projectConfig,"projectConfig");__name(bootstrapProjectCommand,"bootstrapProjectCommand")}});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 runGit2(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit2(["remote","add","fimo",cleanUrl],cwd)}),await runGit2(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit2(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit2(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit2(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit2(["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 fs17 from"node:fs";import path21 from"node:path";function ensurePnpmBuildApproval(targetDir){let yamlPath=path21.join(targetDir,"pnpm-workspace.yaml"),doc={};if(fs17.existsSync(yamlPath))try{doc=import_yaml6.default.parse(fs17.readFileSync(yamlPath,"utf-8"))??{}}catch{return}let allowBuilds=doc.allowBuilds??{},onlyBuilt=Array.isArray(doc.onlyBuiltDependencies)?doc.onlyBuiltDependencies:null;allowBuilds.fimo===!0||onlyBuilt?.includes("fimo")||(doc.allowBuilds={...allowBuilds,fimo:!0},fs17.writeFileSync(yamlPath,import_yaml6.default.stringify(doc)))}function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiUrl,framework}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl};fs17.writeFileSync(path21.join(targetDir,".fimo.settings.json"),`${JSON.stringify(fimoJson,null,2)}
438
438
  `);let initialSiteName=project.displayName?.trim()||project.name,configPath=path21.join(targetDir,"fimo-config.json");if(fs17.existsSync(configPath))try{let config=JSON.parse(fs17.readFileSync(configPath,"utf-8")),seo=config.seo??{};config.seo={...seo,siteName:initialSiteName},fs17.writeFileSync(configPath,`${JSON.stringify(config,null,2)}
439
439
  `)}catch{}let previewScriptUrl=`${apiUrl.replace(/\/+$/,"")}/preview.js`,envLines=[`VITE_API_URL=${tenantApiUrl}`];framework==="next"?envLines.push(`NEXT_PUBLIC_FIMO_API_URL=${tenantApiUrl}`,`NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL=${previewScriptUrl}`):framework==="nuxt"?envLines.push(`NUXT_PUBLIC_FIMO_API_URL=${tenantApiUrl}`,`NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL=${previewScriptUrl}`):framework==="astro"||framework==="sveltekit"?envLines.push(`PUBLIC_FIMO_API_URL=${tenantApiUrl}`,`PUBLIC_FIMO_PREVIEW_SCRIPT_URL=${previewScriptUrl}`):framework==="remix"?envLines.push(`FIMO_API_URL=${tenantApiUrl}`,`FIMO_PREVIEW_SCRIPT_URL=${previewScriptUrl}`):framework==="vite"&&envLines.push(`VITE_FIMO_PREVIEW_SCRIPT_URL=${previewScriptUrl}`);let envPath=path21.join(targetDir,".env"),envBlock=`${envLines.join(`
@@ -1848,7 +1848,7 @@ Next step: open ${path55.join(projectRoot,result.promptPath)} and paste it to yo
1848
1848
  `);return["# Agent Prompt","","Use this prompt with your coding agent inside the migrated Fimo project.","","## Prompt","","Refine this first-pass Fimo migration so it matches the source site much more closely.","","If you are the agent that just ran `fimo migrate`, continue with this rebuild now. Do not treat the CLI scaffold as the final migrated site.","","Read these files in order before editing:","- `AGENTS.md`","- `.claude/skills/fimo/SKILL.md` or the equivalent project `fimo` skill for the current agent","- `.fimo/migrations/current/brief.md`","- `.fimo/migrations/current/manifest.json`","- `.fimo/migrations/current/refine/summary.json`",...pageBriefs.split(`
1849
1849
  `),...manifest.assets.manifest?[`- \`${manifest.assets.manifest}\``]:[],"- `design.md`",...targetModules?targetModules.split(`
1850
1850
  `):["- `src/pages/migrated/`"],"- `src/components/migration/MigrationPageTemplate.tsx` and `src/components/migration/MigrationShell.tsx` if they are still used","","Then rebuild the migrated route(s) with these rules:","- Replace the generic migration template layout with route-specific sections/components wherever needed.","- Preserve the source content hierarchy, navigation labels, CTA labels, and overall visual intent.","- Keep content editable and translatable through Fimo primitives and `t()` calls.","- Use downloaded media from `.fimo/migrations/current/media/` where it improves fidelity; copy `localPath` values from the media map exactly and never derive filenames from source URLs.","- Replace builder forms with live Fimo forms and keep the current draft form JSON as the backend contract.","- Do not copy builder runtime JavaScript or paste raw mirrored HTML as the final implementation.","- Favor clean React code that would be maintainable after the migration is complete.","","Success criteria:","- The refined page looks materially closer to the source site than the default scaffold.","- Placeholder migration copy is removed from the final UI.","- The route still works inside the current Fimo project structure.","- Any imported `.fimo/migrations/current/media/originals/...` asset path resolves to a real file on disk.","- Forms remain wired through Fimo-native mechanisms.","- Importing the generated schemas, forms, entries, and media into Fimo is required, not optional: run `fimo migrate import` to print the exact `fimo assets upload` / `fimo schemas push` / `fimo entries create` / `fimo forms push` commands, then run them. Generated JSON under `.fimo/migrations/current/generated/` is not imported content.","",`Focus: ${focusRoute?`route ${focusRoute}`:"all migrated routes in the current manifest"}.`,`Source site: ${manifest.source.url}`].join(`
1851
- `)}function readGeneratedArtifacts(cwd){let artifactsPath=path55.join(cwd,GENERATED_ARTIFACTS_PATH);if(!fs49.existsSync(artifactsPath))return null;try{return JSON.parse(fs49.readFileSync(artifactsPath,"utf8"))}catch{return null}}function readMediaMap(cwd,manifest){let mediaMapPath=manifest.assets.manifest;if(!mediaMapPath)return[];let fullPath=path55.join(cwd,mediaMapPath);if(!fs49.existsSync(fullPath))return[];try{let parsed=JSON.parse(fs49.readFileSync(fullPath,"utf8"));return Array.isArray(parsed)?parsed.filter(isMigrationMediaMapAsset):[]}catch{return[]}}function isMigrationMediaMapAsset(value){return isRecord2(value)&&typeof value.sourceUrl=="string"&&(typeof value.fileName=="string"||value.fileName===void 0)&&(typeof value.localPath=="string"||value.localPath===null)&&typeof value.status=="string"}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function resolveGeneratedPageModule(cwd,routePath,generatedArtifacts){let expected=path55.join(cwd,"src","pages","migrated",`${pageComponentName2(routePath)}.tsx`);if(fs49.existsSync(expected))return expected;let pageFiles=generatedArtifacts?.pageFiles??[],expectedBase=`${pageComponentName2(routePath)}.tsx`,fallback=pageFiles.map(relativePath=>path55.join(cwd,relativePath)).find(filePath=>path55.basename(filePath)===expectedBase);return fallback&&fs49.existsSync(fallback)?fallback:null}function detectCurrentTemplate(targetModule){return!targetModule||!fs49.existsSync(targetModule)?"custom-or-missing":fs49.readFileSync(targetModule,"utf8").includes("MigrationPageTemplate")?"generic-migration-template":"custom-or-missing"}function routeToBriefFile(routePath){return routePath==="/"?"home":slugify4(routePath.replace(/^\//,"").replace(/\//g,"-"))||"page"}function normalizeRoute(routePath){if(!routePath)return"/";let trimmed=routePath.trim();return trimmed==="/"?"/":`/${trimmed.replace(/^\/+/,"").replace(/\/+$/,"")}`}function normalizeUrlForMatch(value){try{let url=new URL(value);return url.hash="",url.toString()}catch{return value}}function cleanText3(value){return value.replace(/\s+/g," ").trim()}function shouldKeepAction(label){return label.length>=2&&label.length<=80}function absolutizeHref(value,baseUrl){if(!value||value.startsWith("#")||value.startsWith("javascript:")||value.startsWith("mailto:"))return value;try{return new URL(value,baseUrl).toString()}catch{return value}}function writeFile3(cwd,relativePath,content2,written){let fullPath=path55.join(cwd,relativePath);fs49.mkdirSync(path55.dirname(fullPath),{recursive:!0}),fs49.writeFileSync(fullPath,content2,"utf8"),written.push(relativePath)}function unique3(values){let seen=new Set,result=[];for(let value of values){let normalized=value.trim();!normalized||seen.has(normalized)||(seen.add(normalized),result.push(normalized))}return result}function uniqueLinkObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueActionObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.kind}::${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueImageObjects3(values){let seen=new Set,result=[];for(let value of values){let key=`${value.src}::${value.alt??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function pageComponentName2(routePath){if(routePath==="/")return"HomePage";let normalized=`${routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>titleize3(part).replace(/\s+/g,"")).join("")||"Page"}Page`;return/^[A-Za-z_$]/.test(normalized)?normalized:`Route${normalized}`}function titleize3(value){return value.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,match=>match.toUpperCase())}function slugify4(value){return value.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function toPosix3(value){return value.split(path55.sep).join("/")}var REFINE_ROOT,PAGE_BRIEFS_DIR,GENERATED_ARTIFACTS_PATH,init_migrate_refine=__esm({"src/cli/commands/migrate-refine.ts"(){init_dist5();init_slim();init_project();init_migrate();REFINE_ROOT=path55.join(MIGRATION_DIR2,"refine"),PAGE_BRIEFS_DIR=path55.join(REFINE_ROOT,"pages"),GENERATED_ARTIFACTS_PATH=path55.join(MIGRATION_DIR2,"generated","artifacts.json");__name(migrateRefineCommand,"migrateRefineCommand");__name(prepareMigrationRefineArtifacts,"prepareMigrationRefineArtifacts");__name(requireProjectRoot2,"requireProjectRoot");__name(selectPagesForRefine,"selectPagesForRefine");__name(writePageBrief,"writePageBrief");__name(analyzeSourceHtml,"analyzeSourceHtml");__name(buildPageBrief,"buildPageBrief");__name(buildAgentPrompt,"buildAgentPrompt");__name(readGeneratedArtifacts,"readGeneratedArtifacts");__name(readMediaMap,"readMediaMap");__name(isMigrationMediaMapAsset,"isMigrationMediaMapAsset");__name(isRecord2,"isRecord");__name(resolveGeneratedPageModule,"resolveGeneratedPageModule");__name(detectCurrentTemplate,"detectCurrentTemplate");__name(routeToBriefFile,"routeToBriefFile");__name(normalizeRoute,"normalizeRoute");__name(normalizeUrlForMatch,"normalizeUrlForMatch");__name(cleanText3,"cleanText");__name(shouldKeepAction,"shouldKeepAction");__name(absolutizeHref,"absolutizeHref");__name(writeFile3,"writeFile");__name(unique3,"unique");__name(uniqueLinkObjects,"uniqueLinkObjects");__name(uniqueActionObjects,"uniqueActionObjects");__name(uniqueImageObjects3,"uniqueImageObjects");__name(pageComponentName2,"pageComponentName");__name(titleize3,"titleize");__name(slugify4,"slugify");__name(toPosix3,"toPosix")}});function kebabCase(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")}function humanize(field){return field.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/^\w/,c2=>c2.toUpperCase())}function richTextDoc(text3){return{type:"doc",content:[{type:"paragraph",content:[{type:"text",text:text3}]}]}}function placeholderMedia(label){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630"><rect width="100%" height="100%" fill="#e5e7eb"/><text x="50%" y="50%" font-family="sans-serif" font-size="44" fill="#9ca3af" text-anchor="middle" dominant-baseline="middle">${label}</text></svg>`;return{source:"local",url:`data:image/svg+xml;utf8,${encodeURIComponent(svg)}`,alt:`${label} placeholder`,width:1200,height:630,mime:"image/svg+xml",name:"placeholder.svg"}}function exampleDate(n){return new Date(Date.UTC(2024,0,n)).toISOString().slice(0,10)}function exampleReferenceSlug(field){let targetName=field.target??field.targets?.[0];if(!targetName)return;let slug=`${kebabCase(targetName)}-example-1`;return field.many?[slug]:slug}function fillFieldValue(field,def,ctx){let baked=def.default;if(baked!==void 0)return baked;switch(def.type){case"string":return`${humanize(field)} example ${ctx.index}${ctx.localeSuffix}`;case"richtext":return richTextDoc(`Example ${humanize(ctx.schemaName).toLowerCase()} content ${ctx.index}${ctx.localeSuffix}.`);case"number":return ctx.index;case"boolean":return ctx.index%2===1;case"date":return exampleDate(ctx.index);case"json":return{};case"media":return placeholderMedia(humanize(field));case"blocks":return fillBlocks(def,ctx);default:return}}function fillBlocks(def,ctx){if(ctx.depth>=3)return[];let childCtx={...ctx,depth:ctx.depth+1},schema=def.schema;if("oneOf"in schema)return schema.oneOf.slice(0,5).map(variant=>({_type:variant.uid,...fillItem(variant.fields,childCtx)}));let itemCount=def.max===1?1:2;return Array.from({length:itemCount},()=>fillItem(schema.fields,childCtx))}function fillItem(fields,ctx){let item={};for(let[name,def]of Object.entries(fields)){let value=fillFieldValue(name,def,ctx);value!==void 0&&(item[name]=value)}return item}function generateExampleSeed(schema,options={}){let locale=options.locale,localeSuffix=locale?` (${locale})`:"",count=schema.isSingleton?1:Math.max(1,options.count??3),references={},rows=[];for(let i=1;i<=count;i+=1){let row2={};schema.isSingleton||(row2.slug=`${kebabCase(schema.name)}-example-${i}`);for(let[field,def]of Object.entries(schema.fields)){if(schema.examples&&field in schema.examples){row2[field]=schema.examples[field];continue}if(def.type==="reference"){let value2=exampleReferenceSlug(def);value2!==void 0&&(row2[field]=value2,references[field]={...def.target?{target:def.target}:{},...def.targets?{targets:def.targets}:{},by:"slug",...def.many?{many:!0}:{}});continue}let value=fillFieldValue(field,def,{localeSuffix,index:i,schemaName:schema.name,depth:0});value!==void 0&&(row2[field]=value)}rows.push(row2)}return{name:schema.name,isSingleton:schema.isSingleton,localized:schema.localized,rows,references}}var init_example_content=__esm({"src/scripts/cms/example-content.ts"(){__name(kebabCase,"kebabCase");__name(humanize,"humanize");__name(richTextDoc,"richTextDoc");__name(placeholderMedia,"placeholderMedia");__name(exampleDate,"exampleDate");__name(exampleReferenceSlug,"exampleReferenceSlug");__name(fillFieldValue,"fillFieldValue");__name(fillBlocks,"fillBlocks");__name(fillItem,"fillItem");__name(generateExampleSeed,"generateExampleSeed")}});var cms_scaffold_exports={};__export(cms_scaffold_exports,{extractSchemaTypeNames:()=>extractSchemaTypeNames,scaffoldCms:()=>scaffoldCms});function extractSchemaTypeNames(raw){let names=new Set,list=Array.isArray(raw)?raw:raw&&typeof raw=="object"?raw.data??raw.types:null;if(Array.isArray(list))for(let item of list){let name=item&&typeof item=="object"?item.name:void 0;typeof name=="string"&&names.add(name)}return names}function withoutReferences(fields){return Object.fromEntries(Object.entries(fields).filter(([,def])=>def.type!=="reference"))}function hasReferences(fields){return Object.values(fields).some(def=>def.type==="reference")}function orderByDependency(schemas3){let byName=new Map(schemas3.map(schema=>[schema.name,schema])),visited=new Set,ordered=[],visit2=__name((schema,stack)=>{if(!(visited.has(schema.name)||stack.has(schema.name))){stack.add(schema.name);for(let field of Object.values(schema.fields))if(field.type==="reference"){let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets){let dep=byName.get(target);dep&&dep.name!==schema.name&&visit2(dep,stack)}}stack.delete(schema.name),visited.add(schema.name),ordered.push(schema)}},"visit");for(let schema of schemas3)visit2(schema,new Set);return ordered}async function scaffoldCms(opts){let{schemas:schemas3,cms,ctx,api,locales,count=3,force=!1}=opts,existingTypes=opts.existingTypes??new Set,ordered=orderByDependency(schemas3),sp=spinner(`Scaffolding ${cms} content model in Fimo`,{rail:opts.rail??!1}),errorMessage3=__name(error=>error instanceof Error?error.message:String(error),"errorMessage"),schemasCreated=0,entriesCreated=0,skipped=0,failures=[],usedLocales=new Set,created=new Set;try{for(let schema of ordered){if(existingTypes.has(schema.name)&&!force){skipped+=1,created.add(schema.name);continue}force&&await api.deleteSchema(ctx.projectId,schema.name).catch(()=>{});try{await api.createSchema(ctx.projectId,{name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:withoutReferences(schema.fields)}),schemasCreated+=1,created.add(schema.name)}catch(error){failures.push({type:schema.name,stage:"schema",message:errorMessage3(error)})}}for(let schema of ordered)if(!(!created.has(schema.name)||existingTypes.has(schema.name)&&!force||!hasReferences(schema.fields)))try{await api.updateSchema(ctx.projectId,schema.name,{name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:schema.fields})}catch(error){failures.push({type:schema.name,stage:"schema",message:`references: ${errorMessage3(error)}`})}for(let schema of ordered){if(!created.has(schema.name))continue;let seedLocales=schema.localized&&locales.length>0?locales:[void 0];for(let locale of seedLocales){let seed=generateExampleSeed(schema,{count,locale});try{if(schema.isSingleton)await api.putDocument(ctx.projectId,schema.name,seed.rows[0]??{},locale?{locale}:{}),entriesCreated+=1;else{let result=await api.importEntries(ctx.projectId,schema.name,{entries:seed.rows.map(data2=>({data:data2})),...locale?{locale}:{},...Object.keys(seed.references).length>0?{references:seed.references}:{},allowDangling:!0});entriesCreated+=result.created?.length??0,result.failed&&result.failed.length>0&&failures.push({type:schema.name,stage:"entries",message:`${result.failed.length} entry(ies) rejected${locale?` (${locale})`:""}: ${result.failed[0]?.message??result.failed[0]?.code??"unknown"}`})}locale&&usedLocales.add(locale)}catch(error){failures.push({type:schema.name,stage:"entries",message:`${errorMessage3(error)}${locale?` (${locale})`:""}`})}}}let skips=skipped>0?`, ${skipped} already present`:"",issues=failures.length>0?`, ${failures.length} issue(s)`:"";return sp.succeed(`Scaffolded ${schemasCreated} ${cms} type(s) + ${entriesCreated} example entr${entriesCreated===1?"y":"ies"} in Fimo${skips}${issues}`),{cms,schemas:schemasCreated,entries:entriesCreated,locales:[...usedLocales],skipped,failures}}catch(error){throw sp.stop(),error}}var init_cms_scaffold=__esm({"src/cli/utils/cms-scaffold.ts"(){init_dist();init_example_content();__name(extractSchemaTypeNames,"extractSchemaTypeNames");__name(withoutReferences,"withoutReferences");__name(hasReferences,"hasReferences");__name(orderByDependency,"orderByDependency");__name(scaffoldCms,"scaffoldCms")}});function syncStateColor(state,p2){switch(state){case"in-sync":return p2.green("in sync");case"ahead":return p2.blue("ahead");case"behind":return p2.yellow("behind");case"diverged":return p2.red("diverged");default:return p2.dim("unknown")}}function renderStatus2(report,p2,opts={}){let lines=[],sep2=opts.ascii?"|":"\xB7",header=`${p2.bold(`env: ${report.env}`)} ${p2.dim(`vs ${report.vs} ${sep2}`)} ${syncStateColor(report.syncState,p2)}`;if(lines.push(header),lines.push(""),opts.short){for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);if(!delta)continue;let innerSep=opts.ascii?"|":"\xB7",counts=`${delta.changedCount} changed${delta.conflictCount>0?` ${innerSep} ${delta.conflictCount} conflicts`:""}`,truncatedHint=delta.truncated&&delta.items&&delta.items.length<delta.changedCount?p2.dim(` ${innerSep} ${delta.items.length} of ${delta.changedCount} shown`):"";lines.push(` ${p2.bold(name.padEnd(14))} ${p2.dim(counts)}${truncatedHint}`)}return lines.join(`
1851
+ `)}function readGeneratedArtifacts(cwd){let artifactsPath=path55.join(cwd,GENERATED_ARTIFACTS_PATH);if(!fs49.existsSync(artifactsPath))return null;try{return JSON.parse(fs49.readFileSync(artifactsPath,"utf8"))}catch{return null}}function readMediaMap(cwd,manifest){let mediaMapPath=manifest.assets.manifest;if(!mediaMapPath)return[];let fullPath=path55.join(cwd,mediaMapPath);if(!fs49.existsSync(fullPath))return[];try{let parsed=JSON.parse(fs49.readFileSync(fullPath,"utf8"));return Array.isArray(parsed)?parsed.filter(isMigrationMediaMapAsset):[]}catch{return[]}}function isMigrationMediaMapAsset(value){return isRecord2(value)&&typeof value.sourceUrl=="string"&&(typeof value.fileName=="string"||value.fileName===void 0)&&(typeof value.localPath=="string"||value.localPath===null)&&typeof value.status=="string"}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function resolveGeneratedPageModule(cwd,routePath,generatedArtifacts){let expected=path55.join(cwd,"src","pages","migrated",`${pageComponentName2(routePath)}.tsx`);if(fs49.existsSync(expected))return expected;let pageFiles=generatedArtifacts?.pageFiles??[],expectedBase=`${pageComponentName2(routePath)}.tsx`,fallback=pageFiles.map(relativePath=>path55.join(cwd,relativePath)).find(filePath=>path55.basename(filePath)===expectedBase);return fallback&&fs49.existsSync(fallback)?fallback:null}function detectCurrentTemplate(targetModule){return!targetModule||!fs49.existsSync(targetModule)?"custom-or-missing":fs49.readFileSync(targetModule,"utf8").includes("MigrationPageTemplate")?"generic-migration-template":"custom-or-missing"}function routeToBriefFile(routePath){return routePath==="/"?"home":slugify4(routePath.replace(/^\//,"").replace(/\//g,"-"))||"page"}function normalizeRoute(routePath){if(!routePath)return"/";let trimmed=routePath.trim();return trimmed==="/"?"/":`/${trimmed.replace(/^\/+/,"").replace(/\/+$/,"")}`}function normalizeUrlForMatch(value){try{let url=new URL(value);return url.hash="",url.toString()}catch{return value}}function cleanText3(value){return value.replace(/\s+/g," ").trim()}function shouldKeepAction(label){return label.length>=2&&label.length<=80}function absolutizeHref(value,baseUrl){if(!value||value.startsWith("#")||value.startsWith("javascript:")||value.startsWith("mailto:"))return value;try{return new URL(value,baseUrl).toString()}catch{return value}}function writeFile3(cwd,relativePath,content2,written){let fullPath=path55.join(cwd,relativePath);fs49.mkdirSync(path55.dirname(fullPath),{recursive:!0}),fs49.writeFileSync(fullPath,content2,"utf8"),written.push(relativePath)}function unique3(values){let seen=new Set,result=[];for(let value of values){let normalized=value.trim();!normalized||seen.has(normalized)||(seen.add(normalized),result.push(normalized))}return result}function uniqueLinkObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueActionObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.kind}::${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueImageObjects3(values){let seen=new Set,result=[];for(let value of values){let key=`${value.src}::${value.alt??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function pageComponentName2(routePath){if(routePath==="/")return"HomePage";let normalized=`${routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>titleize3(part).replace(/\s+/g,"")).join("")||"Page"}Page`;return/^[A-Za-z_$]/.test(normalized)?normalized:`Route${normalized}`}function titleize3(value){return value.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,match=>match.toUpperCase())}function slugify4(value){return value.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function toPosix3(value){return value.split(path55.sep).join("/")}var REFINE_ROOT,PAGE_BRIEFS_DIR,GENERATED_ARTIFACTS_PATH,init_migrate_refine=__esm({"src/cli/commands/migrate-refine.ts"(){init_dist5();init_slim();init_project();init_migrate();REFINE_ROOT=path55.join(MIGRATION_DIR2,"refine"),PAGE_BRIEFS_DIR=path55.join(REFINE_ROOT,"pages"),GENERATED_ARTIFACTS_PATH=path55.join(MIGRATION_DIR2,"generated","artifacts.json");__name(migrateRefineCommand,"migrateRefineCommand");__name(prepareMigrationRefineArtifacts,"prepareMigrationRefineArtifacts");__name(requireProjectRoot2,"requireProjectRoot");__name(selectPagesForRefine,"selectPagesForRefine");__name(writePageBrief,"writePageBrief");__name(analyzeSourceHtml,"analyzeSourceHtml");__name(buildPageBrief,"buildPageBrief");__name(buildAgentPrompt,"buildAgentPrompt");__name(readGeneratedArtifacts,"readGeneratedArtifacts");__name(readMediaMap,"readMediaMap");__name(isMigrationMediaMapAsset,"isMigrationMediaMapAsset");__name(isRecord2,"isRecord");__name(resolveGeneratedPageModule,"resolveGeneratedPageModule");__name(detectCurrentTemplate,"detectCurrentTemplate");__name(routeToBriefFile,"routeToBriefFile");__name(normalizeRoute,"normalizeRoute");__name(normalizeUrlForMatch,"normalizeUrlForMatch");__name(cleanText3,"cleanText");__name(shouldKeepAction,"shouldKeepAction");__name(absolutizeHref,"absolutizeHref");__name(writeFile3,"writeFile");__name(unique3,"unique");__name(uniqueLinkObjects,"uniqueLinkObjects");__name(uniqueActionObjects,"uniqueActionObjects");__name(uniqueImageObjects3,"uniqueImageObjects");__name(pageComponentName2,"pageComponentName");__name(titleize3,"titleize");__name(slugify4,"slugify");__name(toPosix3,"toPosix")}});function kebabCase(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")}function humanize(field){return field.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/^\w/,c2=>c2.toUpperCase())}function richTextDoc(text3){return{type:"doc",content:[{type:"paragraph",content:[{type:"text",text:text3}]}]}}function placeholderMedia(label){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630"><rect width="100%" height="100%" fill="#e5e7eb"/><text x="50%" y="50%" font-family="sans-serif" font-size="44" fill="#9ca3af" text-anchor="middle" dominant-baseline="middle">${label}</text></svg>`;return{source:"local",url:`data:image/svg+xml;utf8,${encodeURIComponent(svg)}`,alt:`${label} placeholder`,width:1200,height:630,mime:"image/svg+xml",name:"placeholder.svg"}}function exampleDate(n){return new Date(Date.UTC(2024,0,n)).toISOString().slice(0,10)}function exampleReferenceSlug(field){let targetName=field.target??field.targets?.[0];if(!targetName)return;let slug=`${kebabCase(targetName)}-example-1`;return field.many?[slug]:slug}function fillFieldValue(field,def,ctx){let baked=def.default;if(baked!==void 0)return baked;switch(def.type){case"string":return`${humanize(field)} example ${ctx.index}${ctx.localeSuffix}`;case"richtext":return richTextDoc(`Example ${humanize(ctx.schemaName).toLowerCase()} content ${ctx.index}${ctx.localeSuffix}.`);case"number":return ctx.index;case"boolean":return ctx.index%2===1;case"date":return exampleDate(ctx.index);case"json":return{};case"media":return placeholderMedia(humanize(field));case"blocks":return fillBlocks(def,ctx);default:return}}function fillBlocks(def,ctx){if(ctx.depth>=6)return[];let childCtx={...ctx,depth:ctx.depth+1},schema=def.schema;if("oneOf"in schema)return schema.oneOf.slice(0,5).map(variant=>({_type:variant.uid,...fillItem(variant.fields,childCtx)}));let itemCount=def.max===1?1:2;return Array.from({length:itemCount},()=>fillItem(schema.fields,childCtx))}function fillItem(fields,ctx){let item={};for(let[name,def]of Object.entries(fields)){let value=fillFieldValue(name,def,ctx);value!==void 0&&(item[name]=value)}return item}function generateExampleSeed(schema,options={}){let locale=options.locale,localeSuffix=locale?` (${locale})`:"",count=schema.isSingleton?1:Math.max(1,options.count??3),references={},rows=[];for(let i=1;i<=count;i+=1){let row2={};schema.isSingleton||(row2.slug=`${kebabCase(schema.name)}-example-${i}`);for(let[field,def]of Object.entries(schema.fields)){if(schema.examples&&field in schema.examples){row2[field]=schema.examples[field];continue}if(def.type==="reference"){let value2=exampleReferenceSlug(def);value2!==void 0&&(row2[field]=value2,references[field]={...def.target?{target:def.target}:{},...def.targets?{targets:def.targets}:{},by:"slug",...def.many?{many:!0}:{}});continue}let value=fillFieldValue(field,def,{localeSuffix,index:i,schemaName:schema.name,depth:0});value!==void 0&&(row2[field]=value)}rows.push(row2)}return{name:schema.name,isSingleton:schema.isSingleton,localized:schema.localized,rows,references}}var init_example_content=__esm({"src/scripts/cms/example-content.ts"(){__name(kebabCase,"kebabCase");__name(humanize,"humanize");__name(richTextDoc,"richTextDoc");__name(placeholderMedia,"placeholderMedia");__name(exampleDate,"exampleDate");__name(exampleReferenceSlug,"exampleReferenceSlug");__name(fillFieldValue,"fillFieldValue");__name(fillBlocks,"fillBlocks");__name(fillItem,"fillItem");__name(generateExampleSeed,"generateExampleSeed")}});var cms_scaffold_exports={};__export(cms_scaffold_exports,{extractSchemaTypeNames:()=>extractSchemaTypeNames,scaffoldCms:()=>scaffoldCms});function extractSchemaTypeNames(raw){let names=new Set,list=Array.isArray(raw)?raw:raw&&typeof raw=="object"?raw.data??raw.types:null;if(Array.isArray(list))for(let item of list){let name=item&&typeof item=="object"?item.name:void 0;typeof name=="string"&&names.add(name)}return names}function withoutReferences(fields){return Object.fromEntries(Object.entries(fields).filter(([,def])=>def.type!=="reference"))}function hasReferences(fields){return Object.values(fields).some(def=>def.type==="reference")}function orderByDependency(schemas3){let byName=new Map(schemas3.map(schema=>[schema.name,schema])),visited=new Set,ordered=[],visit2=__name((schema,stack)=>{if(!(visited.has(schema.name)||stack.has(schema.name))){stack.add(schema.name);for(let field of Object.values(schema.fields))if(field.type==="reference"){let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets){let dep=byName.get(target);dep&&dep.name!==schema.name&&visit2(dep,stack)}}stack.delete(schema.name),visited.add(schema.name),ordered.push(schema)}},"visit");for(let schema of schemas3)visit2(schema,new Set);return ordered}async function scaffoldCms(opts){let{schemas:schemas3,cms,ctx,api,locales,count=3,force=!1}=opts,existingTypes=opts.existingTypes??new Set,ordered=orderByDependency(schemas3),sp=spinner(`Scaffolding ${cms} content model in Fimo`,{rail:opts.rail??!1}),errorMessage3=__name(error=>error instanceof Error?error.message:String(error),"errorMessage"),schemasCreated=0,entriesCreated=0,skipped=0,failures=[],usedLocales=new Set,created=new Set;try{for(let schema of ordered){if(existingTypes.has(schema.name)&&!force){skipped+=1,created.add(schema.name);continue}force&&await api.deleteSchema(ctx.projectId,schema.name).catch(()=>{});try{await api.createSchema(ctx.projectId,{name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:withoutReferences(schema.fields)}),schemasCreated+=1,created.add(schema.name)}catch(error){failures.push({type:schema.name,stage:"schema",message:errorMessage3(error)})}}for(let schema of ordered)if(!(!created.has(schema.name)||existingTypes.has(schema.name)&&!force||!hasReferences(schema.fields)))try{await api.updateSchema(ctx.projectId,schema.name,{name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:schema.fields})}catch(error){failures.push({type:schema.name,stage:"schema",message:`references: ${errorMessage3(error)}`})}for(let schema of ordered){if(!created.has(schema.name))continue;let seedLocales=schema.localized&&locales.length>0?locales:[void 0];for(let locale of seedLocales){let seed=generateExampleSeed(schema,{count,locale});try{if(schema.isSingleton)await api.putDocument(ctx.projectId,schema.name,seed.rows[0]??{},locale?{locale}:{}),entriesCreated+=1;else{let result=await api.importEntries(ctx.projectId,schema.name,{entries:seed.rows.map(data2=>({data:data2})),...locale?{locale}:{},...Object.keys(seed.references).length>0?{references:seed.references}:{},allowDangling:!0});entriesCreated+=result.created?.length??0,result.failed&&result.failed.length>0&&failures.push({type:schema.name,stage:"entries",message:`${result.failed.length} entry(ies) rejected${locale?` (${locale})`:""}: ${result.failed[0]?.message??result.failed[0]?.code??"unknown"}`})}locale&&usedLocales.add(locale)}catch(error){failures.push({type:schema.name,stage:"entries",message:`${errorMessage3(error)}${locale?` (${locale})`:""}`})}}}let skips=skipped>0?`, ${skipped} already present`:"",issues=failures.length>0?`, ${failures.length} issue(s)`:"";return sp.succeed(`Scaffolded ${schemasCreated} ${cms} type(s) + ${entriesCreated} example entr${entriesCreated===1?"y":"ies"} in Fimo${skips}${issues}`),{cms,schemas:schemasCreated,entries:entriesCreated,locales:[...usedLocales],skipped,failures}}catch(error){throw sp.stop(),error}}var init_cms_scaffold=__esm({"src/cli/utils/cms-scaffold.ts"(){init_dist();init_example_content();__name(extractSchemaTypeNames,"extractSchemaTypeNames");__name(withoutReferences,"withoutReferences");__name(hasReferences,"hasReferences");__name(orderByDependency,"orderByDependency");__name(scaffoldCms,"scaffoldCms")}});function syncStateColor(state,p2){switch(state){case"in-sync":return p2.green("in sync");case"ahead":return p2.blue("ahead");case"behind":return p2.yellow("behind");case"diverged":return p2.red("diverged");default:return p2.dim("unknown")}}function renderStatus2(report,p2,opts={}){let lines=[],sep2=opts.ascii?"|":"\xB7",header=`${p2.bold(`env: ${report.env}`)} ${p2.dim(`vs ${report.vs} ${sep2}`)} ${syncStateColor(report.syncState,p2)}`;if(lines.push(header),lines.push(""),opts.short){for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);if(!delta)continue;let innerSep=opts.ascii?"|":"\xB7",counts=`${delta.changedCount} changed${delta.conflictCount>0?` ${innerSep} ${delta.conflictCount} conflicts`:""}`,truncatedHint=delta.truncated&&delta.items&&delta.items.length<delta.changedCount?p2.dim(` ${innerSep} ${delta.items.length} of ${delta.changedCount} shown`):"";lines.push(` ${p2.bold(name.padEnd(14))} ${p2.dim(counts)}${truncatedHint}`)}return lines.join(`
1852
1852
  `)}let surfaceOpts={ascii:opts.ascii,...opts.all?{maxItems:Number.MAX_SAFE_INTEGER}:{}};for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);delta&&(lines.push(renderSurface(delta,p2,surfaceOpts)),lines.push(""))}if(!opts.surface&&report.crossSurface&&report.crossSurface.length>0&&(lines.push(renderCrossSurface(report.crossSurface,p2,{ascii:opts.ascii})),lines.push("")),report.agents&&report.agents.length>0){lines.push(p2.bold("AGENTS")),lines.push(p2.dim(" declared \xB7 active \xB7 last run"));for(let agent of report.agents){let status=agent.status==="active"?p2.green("active"):agent.status==="paused"?p2.yellow("paused"):p2.red("failed"),lastRun=agent.lastRunAt?p2.dim(new Date(agent.lastRunAt).toISOString().slice(0,19)+"Z"):p2.dim("never");lines.push(` ${agent.name.padEnd(18)} ${status.padEnd(7)} ${lastRun}`)}lines.push("")}return lines.join(`
1853
1853
  `).replace(/\n+$/,"")}var init_render_status=__esm({"src/cli/utils/format/render-status.ts"(){init_esm();init_cross_surface();init_surface();__name(syncStateColor,"syncStateColor");__name(renderStatus2,"renderStatus")}});function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["agents","activations"],["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(resolve9=>{let t2=setTimeout(()=>resolve9({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve9({kind:"ok",value})},error=>{clearTimeout(t2),resolve9({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 runGit2(["status","--porcelain"],cwd)).split(`
1854
1854
  `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path64=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path64,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,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,serverResult]=await Promise.all([codePromise,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,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});return renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii})},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_color();init_render_status();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs56 from"node:fs";import path63 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_detect_framework();init_api();import fs12 from"node:fs";import path13 from"node:path";var import_yaml3=__toESM(require_dist2(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path10 from"node:path";import{z as z3}from"zod";var CapabilityTokenSchema=z3.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z3.array(CapabilityTokenSchema);import{z as z4}from"zod";var CronTriggerSchema=z4.object({type:z4.literal("schedule"),cron:z4.string().min(1,"cron expression required"),tz:z4.string().optional()}),ManualTriggerSchema=z4.object({type:z4.literal("manual")}),WebhookTriggerSchema=z4.object({type:z4.literal("webhook"),path:z4.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z4.discriminatedUnion("type",[ManualTriggerSchema,CronTriggerSchema,WebhookTriggerSchema]),SubAgentRefSchema=z4.object({name:z4.string().min(1),capability_grant:z4.enum(["inherit","explicit"]).optional(),explicit_grants:z4.array(z4.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=z4.object({"sub-agents":z4.array(SubAgentRefSchema)}),RuntimeConfigSchema=z4.object({cloud:z4.boolean().optional(),dev:z4.boolean().optional(),long_running:z4.boolean().optional()}),DataSourceSchema=z4.enum(["main","prod"]),ConfigValueKeySchema=z4.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=z4.preprocess(value=>typeof value=="string"?{key:value}:value,z4.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z4.boolean().default(!0),delivery:z4.literal("process_env").default("process_env")})),IntegrationKeySchema=z4.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z4.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=z4.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z4.object({enabled:z4.boolean().default(!0),tools:z4.record(IntegrationToolKeySchema,z4.boolean()).optional()})),IntegrationPolicySchema=z4.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z4.object({version:z4.literal(1),description:z4.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z4.array(TriggerSchema).optional(),composition:CompositionConfigSchema.optional(),data_sources:z4.array(DataSourceSchema).optional(),secrets:z4.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"]});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 path10.relative(dir,path10.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_yaml3.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=path10.basename(bundlePath),goalPath=path10.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=path10.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(path10.join(bundlePath,"SOUL.md")),capsPath=path10.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=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path10.join(bundlePath,"scripts")),listDir(path10.join(bundlePath,"references")),listDir(path10.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path10.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=path10.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=path10.join(agentsDir,entry.name);if(await fileExists(path10.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var ENTRIES=[{token:"files:read",risk:"low",description:"Read project files"},{token:"files:write",risk:"medium",description:"Write or delete project files"},{token:"cms:read",risk:"low",description:"Read CMS content"},{token:"cms:write",risk:"medium",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",description:"Read uploaded media"},{token:"assets:write",risk:"medium",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",description:"Modify form schemas or clear submissions"},{token:"git:read",risk:"low",description:"Read git state"},{token:"git:branch",risk:"medium",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",runtimeOnly:!0,description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",description:"Read analytics data"},{token:"fimo:preview:read",risk:"low",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"net:fetch",risk:"medium",description:"Make outbound HTTP requests"},{token:"shell:exec",risk:"high",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(e=>[e.token,e])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isHighRisk(token){let def=getCapability(token);return def?.risk==="high"||def?.risk==="critical"}__name(isHighRisk,"isHighRisk");function isRuntimeOnly(token){return getCapability(token)?.runtimeOnly===!0}__name(isRuntimeOnly,"isRuntimeOnly");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}isRuntimeOnly(token)&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is runtime-orchestration-only; agents cannot declare it (the runtime intercepts)`,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?.[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry){return entry?.enabled?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=[],runtimeOnly=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.runtimeOnly&&runtimeOnly.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&runtimeOnly.length===0,unknown,runtimeOnly,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},(_2,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 z5}from"zod";var SurfaceGuardPolicySchema=z5.enum(["block","warn","allow"]),ClassificationSchema=z5.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z5.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z5.object({enabled:z5.boolean(),allowed_skills:z5.array(z5.string().min(1)).default([]),allowed_classifications:z5.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z5.enum(["off","daily","weekly"]),NotificationFormatSchema=z5.object({markdown:z5.boolean().default(!0),html:z5.boolean().default(!1)}),NotificationsPolicySchema=z5.object({email_recipients:z5.array(z5.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z5.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z5.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` shape 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");function requireCloudActivationNotifications(config){let recipients=config?.agents?.notifications?.email_recipients??[];if(recipients.length===0)throw new BundleValidationError("Activating a cloud-time trigger requires `agents.notifications.email_recipients` to be non-empty.",{remediation:"Add at least one email to `fimo-config.json` \u2192 `agents.notifications.email_recipients`. This is where lifecycle proposal emails are sent (mandatory per ADR-0009).",file:"fimo-config.json"});return recipients}__name(requireCloudActivationNotifications,"requireCloudActivationNotifications");import{z as z6}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description,...def.runtimeOnly?{runtimeOnly:!0}:{}}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(d3=>!d3.runtimeOnly).map(d3=>[d3.token,toSpec(d3)]))),CapabilityToken=z6.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z6.array(CapabilityToken);function riskTierOf(cap){let def=VOCABULARY[cap];if(!def)throw new Error(`riskTierOf: '${cap}' is not in the vocabulary`);return def.riskTier}__name(riskTierOf,"riskTierOf");function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");function partitionCapabilities(tokens){let caps=[],unknown=[];for(let t2 of tokens)isCapability(t2)?caps.push(t2):unknown.push(t2);return{caps,unknown}}__name(partitionCapabilities,"partitionCapabilities");function isCritical(cap){return riskTierOf(cap)==="critical"}__name(isCritical,"isCritical");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.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","files.read":"files:read","files.write":"files:write","git.push":"git:push","shell.exec":"shell:exec","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview: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_yaml4=__toESM(require_dist2(),1);function parseCapabilities(yaml){if(yaml==null||yaml.trim().length===0)return{caps:[],errors:[]};let raw;try{raw=(0,import_yaml4.parse)(yaml)}catch(cause){return{caps:[],errors:[{code:"MALFORMED_YAML",message:`invalid YAML: ${cause.message}`,cause}]}}if(raw==null)return{caps:[],errors:[]};if(!Array.isArray(raw))return{caps:[],errors:[{code:"WRONG_SHAPE",message:"capabilities.yaml must be a bare YAML list of capability tokens (not an object)"}]};let caps=[],errors2=[];for(let item of raw){if(typeof item!="string"){errors2.push({code:"WRONG_SHAPE",message:`expected a string capability token, got ${typeof item}`});continue}if(!isCapability(item)){if(CAPABILITY_VOCABULARY.find(d3=>d3.token===item)?.runtimeOnly){errors2.push({code:"RUNTIME_ONLY_CAPABILITY",message:`'${item}' is runtime-orchestration-only \u2014 agents cannot declare it`,token:item});continue}let suggestion=suggestCapability(item)??void 0;errors2.push({code:"UNKNOWN_CAPABILITY",message:suggestion?`unknown capability token '${item}' \u2014 did you mean '${suggestion}'?`:`unknown capability token '${item}'`,token:item,...suggestion?{suggestion}:{}});continue}caps.push(item)}return{caps,errors:errors2}}__name(parseCapabilities,"parseCapabilities");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_api();init_config();init_project();var MAX_TYPE_TO_CONFIRM_ATTEMPTS=3;async function runConsent(input){let{caps,allowShell=!1,quiet=!1,io}=input,{caps:known}=partitionCapabilities(caps);if(renderCapabilityList(known,io),quiet)return known.some(isCritical)?(io.print("! critical-tier capabilities require interactive consent (use --allow-critical only when you understand the risk)"),{decision:"denied",approved:[]}):{decision:"allowed",approved:[...known]};let highRisk=known.filter(isHighRisk);if(highRisk.length===0){let ok=await io.promptYesNo(`? Proceed with install of ${input.agentName}? [y/N]`);return{decision:ok?"allowed":"denied",approved:ok?[...known]:[]}}let approved=known.filter(cap=>!isHighRisk(cap)),denied=[];for(let cap of highRisk.filter(c2=>!isCritical(c2))){if(cap==="shell:exec"&&allowShell){approved.push(cap),io.print(` \u2713 ${cap} (--allow-shell)`);continue}await io.promptYesNo(`? Allow ${cap} for ${input.agentName}? [y/n]`)?approved.push(cap):denied.push(cap)}if(denied.length>0)return io.print(`! aborting install \u2014 denied: ${denied.join(", ")}`),{decision:"denied",approved:[]};for(let cap of highRisk.filter(isCritical)){if(!await typeToConfirm(cap,input.agentName,io))return io.print(`! aborting install \u2014 failed to confirm ${cap}`),{decision:"denied",approved:[]};approved.push(cap)}return{decision:"allowed",approved}}__name(runConsent,"runConsent");async function typeToConfirm(cap,agentName,io){io.print(""),io.print(`! ${agentName} declares the CRITICAL capability '${cap}'`),io.print(" Type the literal token to confirm; anything else aborts.");for(let attempt=1;attempt<=MAX_TYPE_TO_CONFIRM_ATTEMPTS;attempt++){if(await io.promptText(` type '${cap}' (${attempt}/${MAX_TYPE_TO_CONFIRM_ATTEMPTS}): `)===cap)return!0;io.print(" mismatch.")}return!1}__name(typeToConfirm,"typeToConfirm");function renderCapabilityList(caps,io){if(caps.length===0){io.print(" (no capabilities declared \u2014 read-only default trio will apply at runtime)");return}io.print(""),io.print("This agent declares the following capabilities:");let byTier={low:[],medium:[],high:[],critical:[]};for(let cap of caps)byTier[riskTierOf(cap)].push(cap);let ORDER=["low","medium","high","critical"];for(let tier of ORDER){let list=byTier[tier];if(list.length!==0)for(let cap of list.sort())io.print(` \u25CF ${tier.padEnd(8)} ${cap}`)}io.print("")}__name(renderCapabilityList,"renderCapabilityList");function defaultConsentIO(){return{print(line){process.stdout.write(`${line}
@@ -2072,7 +2072,7 @@ export async function fimoCmsList(
2072
2072
  meta: { pagination: { page: 1, pageSize: data.length, pageCount: 1, total: data.length } },
2073
2073
  };
2074
2074
  }
2075
- `}__name(renderStrapiListSource,"renderStrapiListSource");import{existsSync as existsSync14,readdirSync as readdirSync16,readFileSync as readFileSync18}from"node:fs";import{join as join24}from"node:path";var MAX_BLOCK_VARIANTS2=40,MAX_COMPONENT_DEPTH=5,FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,RESERVED_BLOCK_FIELD_NAMES=new Set(["_key","_type"]),COMPONENT_DISCRIMINATOR="__component",TO_MANY=new Set(["oneToMany","manyToMany"]);function pascalCase2(name){return name.replace(/[^a-zA-Z0-9]+(.)?/g,(_2,c2)=>c2?c2.toUpperCase():"").replace(/^(.)/,c2=>c2.toUpperCase())}__name(pascalCase2,"pascalCase");function variantUid(componentUid){let pascal=pascalCase2(componentUid);return/^[A-Za-z]/.test(pascal)?pascal:`Block${pascal}`}__name(variantUid,"variantUid");function mapAttribute(field,attr2,ctx){if(field==="slug")return null;switch(attr2.type){case"password":return null;case"string":case"text":case"email":case"uid":case"enumeration":return{type:"string"};case"richtext":case"blocks":return{type:"richtext"};case"integer":case"biginteger":case"decimal":case"float":return{type:"number"};case"boolean":return{type:"boolean"};case"date":case"datetime":case"time":case"timestamp":return{type:"date"};case"media":return{type:"media"};case"component":return mapComponentAttribute(attr2,ctx);case"dynamiczone":return mapDynamicZone(attr2,ctx);case"json":return{type:"json"};case"relation":{let targetName=attr2.target?ctx.uidToName.get(attr2.target):void 0;return targetName?(attr2.relation?TO_MANY.has(attr2.relation):!1)?{type:"reference",target:targetName,many:!0}:{type:"reference",target:targetName}:{type:"json"}}default:return{type:"json"}}}__name(mapAttribute,"mapAttribute");function componentFields(componentUid,ctx){if(!componentUid||ctx.depth>MAX_COMPONENT_DEPTH||ctx.visiting.has(componentUid))return null;let component=ctx.components.get(componentUid);if(!component)return null;let childCtx={...ctx,depth:ctx.depth+1,visiting:new Set(ctx.visiting).add(componentUid)},fields={};for(let[name,attr2]of Object.entries(component.attributes??{})){if(!FIELD_NAME_PATTERN.test(name)||RESERVED_BLOCK_FIELD_NAMES.has(name)||name===COMPONENT_DISCRIMINATOR)continue;let mapped=mapAttribute(name,attr2,childCtx);mapped&&(fields[name]=mapped)}return fields}__name(componentFields,"componentFields");function mapComponentAttribute(attr2,ctx){let fields=componentFields(attr2.component,ctx);if(!fields)return{type:"json"};let schema={fields};return attr2.repeatable?{type:"blocks",schema}:{type:"blocks",schema,max:1}}__name(mapComponentAttribute,"mapComponentAttribute");function mapDynamicZone(attr2,ctx){let componentUids=attr2.components??[];componentUids.length>MAX_BLOCK_VARIANTS2&&console.warn(`[migration] dynamic zone has ${componentUids.length} components; Fimo blocks allow at most ${MAX_BLOCK_VARIANTS2} variants \u2014 mapping the first ${MAX_BLOCK_VARIANTS2}, dropping ${componentUids.length-MAX_BLOCK_VARIANTS2}.`);let seenUids=new Set,variants=[];for(let componentUid of componentUids.slice(0,MAX_BLOCK_VARIANTS2)){let fields=componentFields(componentUid,ctx);if(!fields)continue;let uid=variantUid(componentUid);for(let n=2;seenUids.has(uid);n+=1)uid=`${variantUid(componentUid)}${n}`;seenUids.add(uid);let component=ctx.components.get(componentUid);variants.push({uid,label:component?.info?.displayName??uid,fields:{[COMPONENT_DISCRIMINATOR]:{type:"string",default:componentUid,editable:!1},...fields}})}return variants.length===0?{type:"json"}:{type:"blocks",schema:{oneOf:variants}}}__name(mapDynamicZone,"mapDynamicZone");function mapSchema(raw,uidToName,components){let info=raw.schema.info??{},name=uidToName.get(raw.uid),fields={},ctx={uidToName,components,visiting:new Set,depth:0};for(let[field,attr2]of Object.entries(raw.schema.attributes??{})){let mapped=mapAttribute(field,attr2,ctx);mapped&&(fields[field]=mapped)}return{name,label:info.displayName||name,isSingleton:raw.schema.kind==="singleType",localized:raw.schema.pluginOptions?.i18n?.localized===!0,fields,sourceUid:raw.uid,sourcePath:`/${info.pluralName??raw.contentTypeName}`}}__name(mapSchema,"mapSchema");function collectRawSchemas(strapiAppDir){let apiDir=join24(strapiAppDir,"src","api");if(!existsSync14(apiDir))return[];let raws=[];for(let apiEntry of readdirSync16(apiDir,{withFileTypes:!0})){if(!apiEntry.isDirectory())continue;let ctRoot=join24(apiDir,apiEntry.name,"content-types");if(existsSync14(ctRoot))for(let ctEntry of readdirSync16(ctRoot,{withFileTypes:!0})){if(!ctEntry.isDirectory())continue;let schemaPath=join24(ctRoot,ctEntry.name,"schema.json");if(existsSync14(schemaPath))try{let schema=JSON.parse(readFileSync18(schemaPath,"utf8"));raws.push({uid:`api::${apiEntry.name}.${ctEntry.name}`,apiName:apiEntry.name,contentTypeName:ctEntry.name,schema})}catch{}}}return raws}__name(collectRawSchemas,"collectRawSchemas");function collectComponents(strapiAppDir){let components=new Map,componentsDir=join24(strapiAppDir,"src","components");if(!existsSync14(componentsDir))return components;for(let categoryEntry of readdirSync16(componentsDir,{withFileTypes:!0})){if(!categoryEntry.isDirectory())continue;let categoryDir=join24(componentsDir,categoryEntry.name);for(let fileEntry of readdirSync16(categoryDir,{withFileTypes:!0})){if(!fileEntry.isFile()||!fileEntry.name.endsWith(".json"))continue;let uid=`${categoryEntry.name}.${fileEntry.name.slice(0,-5)}`;try{let parsed=JSON.parse(readFileSync18(join24(categoryDir,fileEntry.name),"utf8"));components.set(uid,{...parsed,uid})}catch{}}}return components}__name(collectComponents,"collectComponents");function readStrapiSchemas(strapiAppDir){let raws=collectRawSchemas(strapiAppDir),components=collectComponents(strapiAppDir),uidToName=new Map;for(let raw of raws){let singular=raw.schema.info?.singularName??raw.contentTypeName;uidToName.set(raw.uid,pascalCase2(singular))}return raws.map(raw=>mapSchema(raw,uidToName,components)).sort((a,b)=>a.name.localeCompare(b.name))}__name(readStrapiSchemas,"readStrapiSchemas");import{existsSync as existsSync15,readdirSync as readdirSync17,readFileSync as readFileSync19}from"node:fs";import{join as join25,relative as relative6}from"node:path";var SOURCE_EXT_RE2=/\.(tsx?|jsx?|mjs|cjs|astro|vue|svelte)$/,SKIP_DIRS5=new Set(["node_modules",".next",".nuxt",".svelte-kit",".turbo","dist","build","out","coverage",".vercel",".git"]),MAX_FILES=2e3,ENV_REF_RE=/\bSTRAPI[A-Z0-9_]*_URL\b|\bNEXT_PUBLIC_STRAPI[A-Z0-9_]*\b|\bSTRAPI[A-Z0-9_]*_TOKEN\b/,UID_REF_RE=/api::[a-z0-9-]+\.[a-z0-9-]+/,IMPORT_RE=/(?:from\s+|require\(\s*|import\(\s*)['"`]([^'"`]+)['"`]/,ENV_KEY_RE=/^\s*([A-Z0-9_]*STRAPI[A-Z0-9_]*)\s*=/;function readDeps2(dir){try{let pkg=JSON.parse(readFileSync19(join25(dir,"package.json"),"utf8"));return{...pkg.dependencies,...pkg.devDependencies}}catch{return{}}}__name(readDeps2,"readDeps");function classifyLine(line){let importMatch=IMPORT_RE.exec(line);return importMatch&&/strapi/i.test(importMatch[1])&&!/fimo/i.test(importMatch[1])?"strapi-sdk-import":ENV_REF_RE.test(line)?"env-ref":UID_REF_RE.test(line)?"uid-ref":null}__name(classifyLine,"classifyLine");function scanCallSites(frontendDir){let sites=[],scanned=0,walk2=__name(dir=>{if(scanned>=MAX_FILES)return;let entries2;try{entries2=readdirSync17(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(scanned>=MAX_FILES)return;if(entry.isDirectory()){!SKIP_DIRS5.has(entry.name)&&!entry.name.startsWith(".")&&walk2(join25(dir,entry.name));continue}if(!SOURCE_EXT_RE2.test(entry.name))continue;scanned+=1;let full=join25(dir,entry.name),text3;try{text3=readFileSync19(full,"utf8")}catch{continue}let lines=text3.split(`
2075
+ `}__name(renderStrapiListSource,"renderStrapiListSource");import{existsSync as existsSync14,readdirSync as readdirSync16,readFileSync as readFileSync18}from"node:fs";import{join as join24}from"node:path";var MAX_BLOCK_VARIANTS2=40,MAX_COMPONENT_DEPTH=6,FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,RESERVED_BLOCK_FIELD_NAMES=new Set(["_key","_type"]),COMPONENT_DISCRIMINATOR="__component",TO_MANY=new Set(["oneToMany","manyToMany"]);function pascalCase2(name){return name.replace(/[^a-zA-Z0-9]+(.)?/g,(_2,c2)=>c2?c2.toUpperCase():"").replace(/^(.)/,c2=>c2.toUpperCase())}__name(pascalCase2,"pascalCase");function variantUid(componentUid){let pascal=pascalCase2(componentUid);return/^[A-Za-z]/.test(pascal)?pascal:`Block${pascal}`}__name(variantUid,"variantUid");function mapAttribute(field,attr2,ctx){if(field==="slug")return null;switch(attr2.type){case"password":return null;case"string":case"text":case"email":case"uid":case"enumeration":return{type:"string"};case"richtext":case"blocks":return{type:"richtext"};case"integer":case"biginteger":case"decimal":case"float":return{type:"number"};case"boolean":return{type:"boolean"};case"date":case"datetime":case"time":case"timestamp":return{type:"date"};case"media":return{type:"media"};case"component":return mapComponentAttribute(attr2,ctx);case"dynamiczone":return mapDynamicZone(attr2,ctx);case"json":return{type:"json"};case"relation":{let targetName=attr2.target?ctx.uidToName.get(attr2.target):void 0;return targetName?(attr2.relation?TO_MANY.has(attr2.relation):!1)?{type:"reference",target:targetName,many:!0}:{type:"reference",target:targetName}:{type:"json"}}default:return{type:"json"}}}__name(mapAttribute,"mapAttribute");function componentFields(componentUid,ctx){if(!componentUid||ctx.depth>MAX_COMPONENT_DEPTH||ctx.visiting.has(componentUid))return null;let component=ctx.components.get(componentUid);if(!component)return null;let childCtx={...ctx,depth:ctx.depth+1,visiting:new Set(ctx.visiting).add(componentUid)},fields={};for(let[name,attr2]of Object.entries(component.attributes??{})){if(!FIELD_NAME_PATTERN.test(name)||RESERVED_BLOCK_FIELD_NAMES.has(name)||name===COMPONENT_DISCRIMINATOR)continue;let mapped=mapAttribute(name,attr2,childCtx);mapped&&(fields[name]=mapped)}return fields}__name(componentFields,"componentFields");function mapComponentAttribute(attr2,ctx){let fields=componentFields(attr2.component,ctx);if(!fields)return{type:"json"};let schema={fields};return attr2.repeatable?{type:"blocks",schema}:{type:"blocks",schema,max:1}}__name(mapComponentAttribute,"mapComponentAttribute");function mapDynamicZone(attr2,ctx){let componentUids=attr2.components??[];componentUids.length>MAX_BLOCK_VARIANTS2&&console.warn(`[migration] dynamic zone has ${componentUids.length} components; Fimo blocks allow at most ${MAX_BLOCK_VARIANTS2} variants \u2014 mapping the first ${MAX_BLOCK_VARIANTS2}, dropping ${componentUids.length-MAX_BLOCK_VARIANTS2}.`);let seenUids=new Set,variants=[];for(let componentUid of componentUids.slice(0,MAX_BLOCK_VARIANTS2)){let fields=componentFields(componentUid,ctx);if(!fields)continue;let uid=variantUid(componentUid);for(let n=2;seenUids.has(uid);n+=1)uid=`${variantUid(componentUid)}${n}`;seenUids.add(uid);let component=ctx.components.get(componentUid);variants.push({uid,label:component?.info?.displayName??uid,fields:{[COMPONENT_DISCRIMINATOR]:{type:"string",default:componentUid,editable:!1},...fields}})}return variants.length===0?{type:"json"}:{type:"blocks",schema:{oneOf:variants}}}__name(mapDynamicZone,"mapDynamicZone");function mapSchema(raw,uidToName,components){let info=raw.schema.info??{},name=uidToName.get(raw.uid),fields={},ctx={uidToName,components,visiting:new Set,depth:0};for(let[field,attr2]of Object.entries(raw.schema.attributes??{})){let mapped=mapAttribute(field,attr2,ctx);mapped&&(fields[field]=mapped)}return{name,label:info.displayName||name,isSingleton:raw.schema.kind==="singleType",localized:raw.schema.pluginOptions?.i18n?.localized===!0,fields,sourceUid:raw.uid,sourcePath:`/${info.pluralName??raw.contentTypeName}`}}__name(mapSchema,"mapSchema");function collectRawSchemas(strapiAppDir){let apiDir=join24(strapiAppDir,"src","api");if(!existsSync14(apiDir))return[];let raws=[];for(let apiEntry of readdirSync16(apiDir,{withFileTypes:!0})){if(!apiEntry.isDirectory())continue;let ctRoot=join24(apiDir,apiEntry.name,"content-types");if(existsSync14(ctRoot))for(let ctEntry of readdirSync16(ctRoot,{withFileTypes:!0})){if(!ctEntry.isDirectory())continue;let schemaPath=join24(ctRoot,ctEntry.name,"schema.json");if(existsSync14(schemaPath))try{let schema=JSON.parse(readFileSync18(schemaPath,"utf8"));raws.push({uid:`api::${apiEntry.name}.${ctEntry.name}`,apiName:apiEntry.name,contentTypeName:ctEntry.name,schema})}catch{}}}return raws}__name(collectRawSchemas,"collectRawSchemas");function collectComponents(strapiAppDir){let components=new Map,componentsDir=join24(strapiAppDir,"src","components");if(!existsSync14(componentsDir))return components;for(let categoryEntry of readdirSync16(componentsDir,{withFileTypes:!0})){if(!categoryEntry.isDirectory())continue;let categoryDir=join24(componentsDir,categoryEntry.name);for(let fileEntry of readdirSync16(categoryDir,{withFileTypes:!0})){if(!fileEntry.isFile()||!fileEntry.name.endsWith(".json"))continue;let uid=`${categoryEntry.name}.${fileEntry.name.slice(0,-5)}`;try{let parsed=JSON.parse(readFileSync18(join24(categoryDir,fileEntry.name),"utf8"));components.set(uid,{...parsed,uid})}catch{}}}return components}__name(collectComponents,"collectComponents");function readStrapiSchemas(strapiAppDir){let raws=collectRawSchemas(strapiAppDir),components=collectComponents(strapiAppDir),uidToName=new Map;for(let raw of raws){let singular=raw.schema.info?.singularName??raw.contentTypeName;uidToName.set(raw.uid,pascalCase2(singular))}return raws.map(raw=>mapSchema(raw,uidToName,components)).sort((a,b)=>a.name.localeCompare(b.name))}__name(readStrapiSchemas,"readStrapiSchemas");import{existsSync as existsSync15,readdirSync as readdirSync17,readFileSync as readFileSync19}from"node:fs";import{join as join25,relative as relative6}from"node:path";var SOURCE_EXT_RE2=/\.(tsx?|jsx?|mjs|cjs|astro|vue|svelte)$/,SKIP_DIRS5=new Set(["node_modules",".next",".nuxt",".svelte-kit",".turbo","dist","build","out","coverage",".vercel",".git"]),MAX_FILES=2e3,ENV_REF_RE=/\bSTRAPI[A-Z0-9_]*_URL\b|\bNEXT_PUBLIC_STRAPI[A-Z0-9_]*\b|\bSTRAPI[A-Z0-9_]*_TOKEN\b/,UID_REF_RE=/api::[a-z0-9-]+\.[a-z0-9-]+/,IMPORT_RE=/(?:from\s+|require\(\s*|import\(\s*)['"`]([^'"`]+)['"`]/,ENV_KEY_RE=/^\s*([A-Z0-9_]*STRAPI[A-Z0-9_]*)\s*=/;function readDeps2(dir){try{let pkg=JSON.parse(readFileSync19(join25(dir,"package.json"),"utf8"));return{...pkg.dependencies,...pkg.devDependencies}}catch{return{}}}__name(readDeps2,"readDeps");function classifyLine(line){let importMatch=IMPORT_RE.exec(line);return importMatch&&/strapi/i.test(importMatch[1])&&!/fimo/i.test(importMatch[1])?"strapi-sdk-import":ENV_REF_RE.test(line)?"env-ref":UID_REF_RE.test(line)?"uid-ref":null}__name(classifyLine,"classifyLine");function scanCallSites(frontendDir){let sites=[],scanned=0,walk2=__name(dir=>{if(scanned>=MAX_FILES)return;let entries2;try{entries2=readdirSync17(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(scanned>=MAX_FILES)return;if(entry.isDirectory()){!SKIP_DIRS5.has(entry.name)&&!entry.name.startsWith(".")&&walk2(join25(dir,entry.name));continue}if(!SOURCE_EXT_RE2.test(entry.name))continue;scanned+=1;let full=join25(dir,entry.name),text3;try{text3=readFileSync19(full,"utf8")}catch{continue}let lines=text3.split(`
2076
2076
  `);for(let i=0;i<lines.length;i+=1){let reason=classifyLine(lines[i]);reason&&sites.push({file:relative6(frontendDir,full),line:i+1,reason,snippet:lines[i].trim().slice(0,200)})}}},"walk");return walk2(frontendDir),sites}__name(scanCallSites,"scanCallSites");function scanEnvKeys(frontendDir){let keys=new Set;for(let name of[".env",".env.local",".env.development",".env.production"]){let file=join25(frontendDir,name);if(existsSync15(file))try{for(let line of readFileSync19(file,"utf8").split(`
2077
2077
  `)){let match=ENV_KEY_RE.exec(line);match&&keys.add(match[1])}}catch{}}return[...keys]}__name(scanEnvKeys,"scanEnvKeys");function detectStrapiTouchpoints(frontendDir){let dependencies=Object.keys(readDeps2(frontendDir)).filter(name=>/strapi/i.test(name)),callSites=scanCallSites(frontendDir),envVars=scanEnvKeys(frontendDir);return{dependencies,callSites,envVars,clean:dependencies.length===0&&callSites.length===0}}__name(detectStrapiTouchpoints,"detectStrapiTouchpoints");import fs44 from"node:fs";import path48 from"node:path";import{parseSync as parseSync8}from"oxc-parser";function shapesFrom(fields){let shapes={};for(let[name,def]of Object.entries(fields))if(def.type==="blocks")if("oneOf"in def.schema){let variants={};for(let variant of def.schema.oneOf){let nested=shapesFrom(variant.fields);Object.keys(nested).length>0&&(variants[variant.uid]=nested)}shapes[name]={kind:"list",...Object.keys(variants).length>0?{variants}:{}}}else{let nested=shapesFrom(def.schema.fields);shapes[name]={kind:def.max===1?"single":"list",...Object.keys(nested).length>0?{fields:nested}:{}}}return shapes}__name(shapesFrom,"shapesFrom");function computeFieldShapes(schemas3){let byType={};for(let schema of schemas3){let shapes=shapesFrom(schema.fields);Object.keys(shapes).length>0&&(byType[schema.name]=shapes)}return byType}__name(computeFieldShapes,"computeFieldShapes");function strapiWiring(schemas3){let types={},singletons=[];for(let schema of schemas3){let pluralName=schema.sourcePath.replace(/^\/+/,"");pluralName&&(types[pluralName]=schema.name),schema.isSingleton&&singletons.push(schema.name)}return{types,singletons}}__name(strapiWiring,"strapiWiring");function renderFimoStrapiModule(schemas3){let{types,singletons}=strapiWiring(schemas3),typeEntries=Object.entries(types).map(([pluralName,typeName])=>` '${pluralName}': '${typeName}',`).join(`
2078
2078
  `),fieldShapes=JSON.stringify(computeFieldShapes(schemas3),null,2);return`// AUTO-GENERATED by \`fimo migrate --scaffold-cms\`. Serves this site's Strapi