fimo 0.10.0-staging.1 → 0.10.0-staging.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "bundled": true,
3
3
  "bundler": "esbuild",
4
- "bundledAt": "2026-07-27T07:55:40.361Z",
4
+ "bundledAt": "2026-07-27T11:17:03.341Z",
5
5
  "cliVersion": "0.9.0",
6
6
  "external": [
7
7
  "oxc-parser",
package/dist/cli/index.js CHANGED
@@ -192,7 +192,7 @@ description: Fimo project rules
192
192
  alwaysApply: true
193
193
  ---
194
194
 
195
- ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}return selected.has("windsurf")&&writeIfMissing(".windsurfrules",agentsMdContent),selected.has("gemini-cli")&&writeIfMissing("GEMINI.md",agentsMdContent),result}function syncPerAgentVariants(targetDir,agents){let agentsMdPath=path9.join(targetDir,"AGENTS.md");if(!fs9.existsSync(agentsMdPath))throw new Error(`No AGENTS.md found in ${targetDir}. Run \`fimo create\` first, or create AGENTS.md manually before running \`fimo rules sync\`.`);let agentsMdContent=fs9.readFileSync(agentsMdPath,"utf8");return writePerAgentVariants(targetDir,agents,agentsMdContent)}function detectAgentsInProject(cwd){let detected=[];return fs9.existsSync(path9.join(cwd,"CLAUDE.md"))&&detected.push("claude-code"),fs9.existsSync(path9.join(cwd,".cursor","rules","fimo.mdc"))&&detected.push("cursor"),fs9.existsSync(path9.join(cwd,".windsurfrules"))&&detected.push("windsurf"),fs9.existsSync(path9.join(cwd,"GEMINI.md"))&&detected.push("gemini-cli"),detected}var TEMPLATE_ROOT,AGENT_TEMPLATES_ROOT,EXCLUDED_DIRS,init_scaffold=__esm({"src/cli/utils/scaffold.ts"(){init_templates();init_config();init_templates();TEMPLATE_ROOT=getTemplatePath("react-router"),AGENT_TEMPLATES_ROOT=path9.resolve(CLI_ROOT,"assets","agent-templates"),EXCLUDED_DIRS=new Set(["node_modules","dist","build",".turbo",".git"]);__name(resolveTemplateRoot,"resolveTemplateRoot");__name(resolveAgentTemplatesRoot,"resolveAgentTemplatesRoot");__name(resolveAgentTemplate,"resolveAgentTemplate");__name(listAgentTemplates,"listAgentTemplates");__name(copyAgentTemplate,"copyAgentTemplate");__name(copyTemplate,"copyTemplate");__name(pinFimoDependency,"pinFimoDependency");__name(copyTree,"copyTree");__name(writePerAgentVariants,"writePerAgentVariants");__name(syncPerAgentVariants,"syncPerAgentVariants");__name(detectAgentsInProject,"detectAgentsInProject")}});import{z as z5}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z5.ZodOptional||schema instanceof z5.ZodNullable||schema instanceof z5.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z5.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z5.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 z5.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z5.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 z5.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 z5.ZodObject)return createObjectDTO(schema);if(schema instanceof z5.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 z6}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z6.object({data:dataSchema}),"createResponseSchema")}});import{z as z7}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z7.object({page:z7.coerce.number().int().positive().default(1),limit:z7.coerce.number().int().positive().max(100).default(20)})}});import{z as z8}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:z8.coerce.date(),positiveInt:z8.number().int().positive(),nonNegativeInt:z8.number().int().nonnegative()},BaseEntitySchema=z8.object({id:z8.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z8.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z8.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z8.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z8.enum(["public","private"]),ProjectStatusSchema=z8.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z8.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z8.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z8.enum(["owner","admin","member"]),AssetTypeSchema=z8.enum(["file","folder"]),TemplateCodeSchema=z8.enum(["Free","Premium"]),FieldTypeSchema=z8.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 z9}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=z9.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 z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path47){let conditionPath=[...path47,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path47)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","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=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops: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=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops: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=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)})}});import{z as z14}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:z14.string(),displayName:z14.string().nullable(),subdomain:z14.string().nullable().optional(),subdomainUpdatedAt:z14.date().nullable().optional(),organizationId:z14.string().nullable(),createdBy:z14.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z14.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z14.string(),thumbnailUrl:z14.string().nullable(),publishedThumbnailUrl:z14.string().nullable(),category:z14.string().nullable(),appUrl:z14.string().nullable(),lastPublishedAt:z14.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z14.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z14.object({id:z14.uuid(),name:z14.string(),displayName:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),visibility:ProjectVisibilitySchema,category:z14.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z14.object({id:z14.string(),name:z14.string(),avatar:z14.string().nullable(),color:z14.object({bg:z14.string(),text:z14.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z14.object({path:z14.string(),content:z14.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z14.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z14.object({id:z14.string(),messageId:z14.string(),versionId:z14.string().nullable(),role:ProjectChatMessageRole,parts:z14.array(z14.any()),createdAt:z14.coerce.date()}),MessageUserMetadataSchema=z14.object({id:z14.string(),name:z14.string().nullable().optional(),image:z14.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z14.object({shortTitle:z14.string().optional(),questions:z14.array(z14.object({header:z14.string(),question:z14.string(),answer:z14.string(),selectedLabels:z14.array(z14.string()),freeText:z14.string(),skipped:z14.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z14.number(),metadata:z14.object({user:MessageUserMetadataSchema,changeManifest:z14.array(z14.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z14.object({id:z14.uuid(),versionId:z14.string(),projectId:z14.uuid(),commitHash:z14.string(),name:z14.string(),description:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z14.object({content:z14.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z14.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z14.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z14.object({success:z14.boolean(),message:z14.string().optional()})),ProjectPublicationStateDTOSchema=z14.object({isPublished:z14.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z14.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z14.object({success:z14.boolean(),message:z14.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z15}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=z15.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z15.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z15.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z15.string().nullable(),deletedAt:z15.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z15.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z15.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z15.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z15.object({surface:z15.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z15.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z15.number().int().nonnegative(),conflictCount:z15.number().int().nonnegative()}),EnvDiffResultSchema=z15.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z15.coerce.date(),surfaces:z15.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z16}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=z16.object({success:z16.literal(!0),downloadUrl:z16.string(),expiresAt:z16.string(),fileSize:z16.number(),duration:z16.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z16.object({success:z16.literal(!0),projectId:z16.string(),projectName:z16.string(),displayName:z16.string(),projectUrl:z16.string(),duration:z16.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z16.object({contentTypes:z16.number(),entries:z16.number(),assets:z16.number(),translations:z16.number(),forms:z16.number(),codeFiles:z16.number(),assetFiles:z16.number()}),ImportPreviewSurfaceDTOSchema=z16.object({name:z16.string(),included:z16.boolean(),count:z16.number().optional(),note:z16.string().optional()}),ImportPreviewDTOSchema=z16.object({projectName:z16.string(),displayName:z16.string().nullable(),visibility:z16.string().nullable(),category:z16.string().nullable(),exportedAt:z16.string(),version:z16.string(),envScope:z16.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z16.array(ImportPreviewSurfaceDTOSchema),fileSize:z16.number(),fileName:z16.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z16.object({success:z16.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z17}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=z17.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z17.object({type:z17.literal("manual")}),ScheduleTriggerSchema=z17.object({type:z17.literal("schedule"),cron:z17.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:z17.string().optional()}),WebhookTriggerSchema2=z17.object({type:z17.literal("webhook"),path:z17.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z17.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z18}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=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z18.object({projectId:z18.uuid(),env:EnvSchema,agentName:z18.string().min(1),triggerIndex:z18.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z18.boolean(),lastFiredAt:z18.coerce.date().nullable(),webhookPath:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z18.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z18.object({error:z18.literal("webhook_path_taken"),conflictAgent:z18.string(),path:z18.string()}),ManualRunRequestSchema=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,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=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemActivationSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z20.string().min(1),active:z20.boolean()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),activations:z20.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}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=z21.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z21.object({cpuMs:z21.number().nonnegative().default(0),netBytes:z21.number().nonnegative().default(0),walltimeMs:z21.number().nonnegative().default(0),llmTokensIn:z21.number().nonnegative().optional(),llmTokensOut:z21.number().nonnegative().optional()}),AgentSessionDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),env:EnvSchema,agentName:z21.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z21.unknown().optional(),capabilities:z21.array(z21.string()).optional(),dataSources:z21.array(z21.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z21.string().nullable(),startedAt:z21.coerce.date().nullable(),finishedAt:z21.coerce.date().nullable(),cancelledAt:z21.coerce.date().nullable(),costUsd:z21.number().nonnegative(),costCeilingUsd:z21.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z21.boolean(),lastCheckpointId:z21.uuid().nullable(),branchEnvId:z21.uuid().nullable(),parentSessionId:z21.uuid().nullable(),terminalReason:z21.string().nullable(),errorMessage:z21.string().nullable(),report:z21.string().nullable(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z21.object({id:z21.uuid(),sessionId:z21.uuid(),checkpointIdx:z21.number().int().nonnegative(),payloadRef:z21.string(),payloadSizeBytes:z21.number().int().nonnegative(),checksum:z21.string().length(64),createdAt:z21.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z21.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z21.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z21.object({session:AgentSessionDTOSchema,checkpoints:z21.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z21.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z21.object({reason:z21.string().min(1).max(120).optional()})}});import{z as z22}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=z22.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z22.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z22.object({id:z22.uuid(),envId:z22.uuid(),sessionId:z22.uuid().nullable(),skillName:z22.string().min(1),classification:AgentBranchClassificationSchema,rationale:z22.string().nullable(),summary:z22.string().nullable(),surfaceDeltas:z22.record(z22.string(),z22.unknown()),createdAt:z22.coerce.date(),decidedAt:z22.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z22.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z22.object({path:z22.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z22.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z22.object({code:z22.literal("merge_conflict"),message:z22.string(),conflicts:z22.record(z22.string(),z22.number().int().nonnegative())})}});import{z as z23}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=z23.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z23.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z23.enum(["secret_text"]),IntegrationCredentialUsageSchema=z23.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z23.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z23.object({mode:IntegrationAuthModeSchema,label:z23.string().min(1),description:z23.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z23.object({id:z23.string().min(1),label:z23.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z23.boolean()}),IntegrationToolDefinitionDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),description:z23.string().min(1)}),IntegrationRecipeDTOSchema=z23.object({title:z23.string().min(1),description:z23.string().min(1),command:z23.string().min(1).optional()}),IntegrationInfoDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),summary:z23.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z23.array(IntegrationAuthModeDTOSchema),credentials:z23.array(IntegrationCredentialDefinitionDTOSchema),tools:z23.array(IntegrationToolDefinitionDTOSchema),recipes:z23.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),installed:z23.boolean(),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z23.string().nullable(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),installedAt:z23.coerce.date().nullable(),updatedAt:z23.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z23.string(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z23.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z23.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z23.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z23.object({value:z23.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z23.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z23.object({id:z23.uuid(),organizationId:z23.string().min(1),integrationKey:z23.string().min(1),alias:z23.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z23.string().min(1),externalAccountName:z23.string().nullable(),externalBotUserId:z23.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z23.array(z23.string()),connectedAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z23.object({alias:z23.string().min(1).max(120).optional(),token:z23.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z23.object({integrationKey:z23.string().min(1),connectUrl:z23.string().url(),expiresAt:z23.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z23.object({ref:z23.string().min(1),connectionAlias:z23.string().min(1).optional(),agentName:z23.string().min(1).max(160).nullable().optional(),force:z23.boolean().optional()}),ProjectChannelBindingDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),connectionId:z23.uuid(),externalWorkspaceId:z23.string().min(1),externalChannelId:z23.string().min(1),externalChannelName:z23.string().nullable(),agentName:z23.string().nullable(),enabled:z23.boolean(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z23.object({markdown:z23.boolean().optional(),summary:z23.boolean().optional(),links:z23.boolean().optional(),images:z23.boolean().optional(),html:z23.union([z23.literal("cleaned"),z23.literal("raw"),z23.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z23.object({url:z23.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z23.object({query:z23.string().min(1),maxResults:z23.number().int().positive().max(20).optional(),sources:z23.array(z23.enum(["web","news","images"])).min(1).max(3).optional(),categories:z23.array(z23.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z23.enum(["hour","day","week","month","year"]).optional(),location:z23.string().min(1).max(160).optional(),country:z23.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z23.object({url:z23.string().url(),search:z23.string().min(1).optional(),limit:z23.number().int().positive().max(200).optional(),includeSubdomains:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z23.object({url:z23.string().url(),limit:z23.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z23.object({text:z23.string().min(1).max(200).optional(),cron:z23.string().min(1).max(120).optional(),timezone:z23.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z23.object({type:z23.enum(["scrape","crawl"]).default("scrape"),urls:z23.array(z23.string().url()).min(1).max(50),scrapeOptions:z23.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z23.object({name:z23.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z23.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z23.string().min(1).max(2e3).optional(),judgeEnabled:z23.boolean().optional(),retentionDays:z23.number().int().min(1).max(365).optional(),notification:z23.object({email:z23.object({enabled:z23.boolean().default(!0),recipients:z23.array(z23.string().email()).min(1).max(20),includeDiffs:z23.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z23.object({monitorId:z23.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z23.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z23.object({connectionAlias:z23.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z23.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.list"),input:z23.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z23.object({provider:z23.string().min(1),providerCredits:z23.number().nonnegative().optional(),providerCostUsd:z23.number().nonnegative().optional(),requests:z23.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z23.object({credits:z23.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()}),FirecrawlSearchToolOutputSchema=z23.object({query:z23.string(),provider:z23.literal("firecrawl"),warning:z23.string().optional(),results:z23.array(z23.object({title:z23.string(),url:z23.string(),snippet:z23.string().optional(),content:z23.string().optional(),score:z23.number().optional(),publishedAt:z23.string().optional()}))}),FirecrawlMapToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),count:z23.number(),links:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),description:z23.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),total:z23.number(),pages:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()})),warning:z23.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z23.object({cron:z23.string().optional(),text:z23.string().optional(),timezone:z23.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z23.object({id:z23.string().optional(),urls:z23.array(z23.string()).optional(),scrapeOptions:z23.record(z23.string(),z23.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z23.object({id:z23.string(),name:z23.string(),status:z23.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z23.string().nullable().optional(),lastRunAt:z23.string().nullable().optional(),currentCheckId:z23.string().nullable().optional(),targets:z23.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z23.string().nullable().optional(),judgeEnabled:z23.boolean().optional(),estimatedCreditsPerMonth:z23.number().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z23.object({id:z23.string(),monitorId:z23.string(),scheduledFor:z23.string().nullable().optional(),startedAt:z23.string().nullable().optional(),finishedAt:z23.string().nullable().optional(),estimatedCredits:z23.number().optional(),reservedCredits:z23.number().optional(),actualCredits:z23.number().optional(),billingStatus:z23.string().nullable().optional(),summary:z23.object({totalPages:z23.number().optional(),same:z23.number().optional(),changed:z23.number().optional(),new:z23.number().optional(),removed:z23.number().optional(),error:z23.number().optional()}).passthrough().optional(),error:z23.string().nullable().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitors:z23.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),deleted:z23.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),checks:z23.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),check:FirecrawlMonitorCheckOutputSchema,next:z23.string().optional()}),FirecrawlToolKeySchema=z23.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z23.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z23.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z23.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z23.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z23.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 z24}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=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable(),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema))}});import{z as z25}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=z25.object({id:z25.uuid(),occurredAt:z25.coerce.date(),projectId:z25.uuid().nullable(),env:z25.string().nullable(),actor:z25.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z25.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z25.unknown().optional(),ipAddress:z25.string().nullable().optional(),userAgent:z25.string().nullable().optional(),error:z25.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z25.object({rows:z25.array(AuditLogRowDTOSchema),nextCursor:z25.string().nullable()})),AuditLogQuerySchema=z25.object({env:z25.string().optional(),action:AuditActionSchema.optional(),actor:z25.string().optional(),from:z25.coerce.date().optional(),to:z25.coerce.date().optional(),limit:z25.coerce.number().int().min(1).max(200).optional(),cursor:z25.string().optional()})}});import{z as z26}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,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=z26.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({env:EnvSchema,vs:EnvSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),triggerKind:z26.string(),triggerSpec:z26.record(z26.string(),z26.unknown()),enabled:z26.boolean(),emailRecipients:z26.array(z26.string()).nullable(),qstashScheduleId:z26.string().nullable()}),ActivationDiffSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:z26.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity"]).optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:EnvSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}from"zod";var 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=z27.object({surface:SurfaceNameSchema,key:z27.string(),label:z27.string()}),InlineSchema=z27.object({text:z27.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z27.discriminatedUnion("type",[z27.object({type:z27.literal("paragraph"),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("preview"),ref:DiffRefSchema,caption:z27.string().optional()}),z27.object({type:z27.literal("code"),code:z27.string(),lang:z27.string().optional(),caption:z27.string().optional()}),z27.object({type:z27.literal("risk"),level:z27.enum(["warning","error"]),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("list"),items:z27.array(z27.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z27.object({headline:z27.string(),blocks:z27.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z27.object({summary:EnvDiffSummarySchema,fingerprint:z27.string(),generatedAt:z27.coerce.date(),cached:z27.boolean().optional(),credits:z27.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z28}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=z28.object({date:z28.string(),visitors:z28.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z28.object({key:z28.string(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z28.object({path:z28.string(),pageName:z28.string().nullable().optional(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z28.object({preset:z28.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z28.string(),requestedTo:z28.string(),effectiveFrom:z28.string(),effectiveTo:z28.string(),isRetentionLimited:z28.boolean(),groupBy:z28.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z28.object({date:z28.string(),content:z28.string(),updatedAt:z28.string(),updatedByUserId:z28.string()}),ProjectPageviewAnalyticsDTOSchema=z28.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative(),bounceRate:z28.number().min(0).max(100),viewsPerVisit:z28.number().nonnegative(),averageVisitDurationSeconds:z28.number().nonnegative(),visitorsSeries:z28.array(ProjectDailyVisitorsDTOSchema),topPages:z28.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z28.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z29}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=z29.object({id:z29.string(),email:z29.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z29.coerce.date(),createdAt:z29.coerce.date(),inviterUserId:z29.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z29.object({id:z29.string(),token:z29.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z29.object({success:z29.boolean(),projectId:z29.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z30}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=z30.object({id:z30.string(),name:z30.string(),image:z30.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z30.object({count:z30.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z30.object({counts:z30.object({signed_up:z30.int(),activated:z30.int()}),credits:z30.object({total:z30.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z30.email(),emailVerified:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z31}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=z31.object({id:z31.string(),principalType:ProjectPrincipalTypeSchema,principalId:z31.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z31.coerce.date(),expiresAt:z31.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z31.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z31.record(z31.string(),z31.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z31.object({access:z31.array(ProjectAccessItemDTOSchema),invites:z31.array(ProjectInviteDTOSchema),organization:z31.object({name:z31.string().nullable(),logo:z31.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z31.object({success:z31.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z31.object({success:z31.boolean(),projectId:z31.uuid()}))}});import{z as z32}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=z32.object({publicationStatus:PublicationStatusSchema,appUrl:z32.string().nullable(),lastPublishedAt:z32.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z33}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=z33.object({url:z33.url(),expiresAt:z33.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z33.discriminatedUnion("source",[z33.object({source:z33.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z33.null()}),z33.object({source:z33.literal("dev"),artifact:z33.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z34}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:z34.string(),slug:z34.string().nullable(),logo:z34.string().nullable(),metadata:z34.record(z34.string(),z34.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),email:z34.email(),image:z34.string().nullable()}),OrganizationMemberDTOSchema=z34.object({id:z34.string(),userId:z34.string(),organizationId:z34.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z34.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z35}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=z35.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z35.object({reason:CancellationReasonCodeSchema,details:z35.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z35.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z35.object({included:z35.number().optional(),unitPrice:z35.number().optional(),dailyCap:z35.number().nullable().optional()}),EntitlementsDTOSchema=z35.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z35.object({retentionDays:z35.number().int().positive(),canUseExtendedDateRanges:z35.boolean()}).optional(),members:z35.object({canInvite:z35.boolean(),maxMembers:z35.number().int().positive().nullable()}).optional(),projects:z35.object({canCreatePrivateProjects:z35.boolean(),maxPrivateProjects:z35.number().int().positive().nullable()}).optional(),domains:z35.object({canUseCustomDomains:z35.boolean(),maxDomains:z35.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z35.object({id:z35.string(),external_id:z35.string(),customerId:z35.string(),planId:z35.string(),planCode:TemplateCodeSchema,currentPeriod:z35.object({start:z35.string(),end:z35.string().nullable()}),cancelAt:z35.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z35.string(),nextPaymentAt:z35.string().nullable(),baseAmount:z35.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z35.object({totalCap:z35.number(),dailyCap:z35.number(),usedTotal:z35.number()}),CreditBalanceDTOSchema=z35.object({total:z35.number(),base:z35.number(),dailyBase:z35.number(),purchases:z35.number(),awards:z35.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z35.object({total:z35.number(),nearLimit:z35.boolean(),canChat:z35.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z35.object({dailyFreeAvailable:z35.number(),monthlyAvailable:z35.number(),purchasedAvailable:z35.number(),awardedAvailable:z35.number()}),ProjectDailyCreditAllowanceDTOSchema=z35.object({periodCap:z35.number(),dailyGrant:z35.number(),usedThisPeriod:z35.number(),remainingThisPeriod:z35.number()}),ProjectCreditBalanceDTOSchema=z35.object({projectId:z35.uuid(),organizationId:z35.string(),balance:z35.object({totalAvailable:z35.number(),nearLimit:z35.boolean(),canUseAi:z35.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z35.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z35.object({invoiceId:z35.string(),newBalance:z35.int(),creditCount:z35.int(),amountUsd:z35.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z35.object({url:z35.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 z36}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=z36.object({brand:z36.string(),last4:z36.string(),exp:z36.string(),isDefault:z36.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z37}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z37.string().superRefine((path47,ctx)=>{let segments=path47.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=z37.object({type:z37.literal("renameField"),contentType:z37.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z37.object({enabled:z37.boolean()}).strict(),ContentTypeDTOSchema=z37.object({id:z37.string(),name:z37.string(),label:z37.string(),isSingleton:z37.boolean(),i18n:ContentTypeI18nSchema,fields:z37.record(z37.string(),FieldDefinitionSchema),createdAt:z37.string(),updatedAt:z37.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z37.object({contentTypes:z37.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z37.object({id:z37.string(),entryId:z37.string(),documentId:z37.string(),slug:z37.string(),locale:z37.string().optional(),createdAt:z37.string(),updatedAt:z37.string(),__fimo:z37.object({contentType:z37.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({limit:z37.number(),offset:z37.number(),total:z37.number(),hasMore:z37.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z37.object({contentType:z37.string(),count:z37.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z37.object({counts:z37.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z37.object({count:z37.number().int().nonnegative(),sourceLocale:z37.string(),targetLocale:z37.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z37.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z37.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z37.union([z37.string(),z37.number(),z37.boolean(),z37.null()]),entryWhereOperatorSchema=z37.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z37.array(entryWhereScalarSchema).optional(),$nin:z37.array(entryWhereScalarSchema).optional(),$contains:z37.string().optional(),$startsWith:z37.string().optional(),$null:z37.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z37.object({data:z37.record(z37.string(),z37.unknown()),locale:z37.string().min(1).optional(),documentId:z37.uuid().optional()}),entryIdsSchema=z37.array(z37.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z37.object({sql:z37.string().min(1)}),BulkCreateEntriesRequestSchema=z37.object({entries:z37.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z37.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z37.object({updates:z37.array(z37.object({id:z37.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,locale:z37.string().min(1).optional()}),z37.object({where:EntryWhereSchema,locale:z37.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z37.object({data:z37.array(z37.record(z37.string(),z37.unknown())),meta:z37.object({rowCount:z37.number().int().nonnegative(),truncated:z37.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({created:z37.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({updated:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({deleted:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z38}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z38.object({index:z38.number().int().nonnegative(),contentType:z38.string(),field:z38.string(),value:z38.string(),against:z38.enum(["stored","batch"]),ownerDocumentId:z38.uuid().optional(),ownerIndex:z38.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z38.object({code:z38.literal("unique_conflict"),message:z38.string(),conflicts:z38.array(UniqueConflictSchema),truncated:z38.boolean().optional()})}});import{z as z39}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z39.object({kind:z39.literal("unique_conflict"),contentType:z39.string(),field:z39.string(),value:z39.string(),documentCount:z39.number().int().positive(),documentIds:z39.array(z39.uuid()),documentIdsTruncated:z39.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z39.object({code:z39.literal("schema_transition_rejected"),message:z39.string(),issues:z39.array(SchemaTransitionIssueSchema),truncated:z39.boolean().optional()})}});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";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z51.object({translated:z51.number().int().nonnegative(),total:z51.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z51.object({locale:z51.string(),isDefault:z51.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z51.object({defaultLocale:z51.string(),routing:z51.object({strategy:z51.literal("path-prefix"),prefixDefaultLocale:z51.boolean()}),locales:z51.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z51.object({locale:z51.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z51.object({locale:z51.string().min(1).max(40)}),ProjectLocaleMutationSchema=z51.object({locale:z51.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z51.object({locale:z51.string(),entriesDeleted:z51.number().int().nonnegative(),labelsDeleted:z51.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z52}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=z52.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z52.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=z52.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z52.number(),credits:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z53}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=z53.object({options:z53.record(z53.string(),z53.unknown()),name:z53.string().optional(),parentId:z53.string().nullable().optional(),altText:z53.string().optional(),caption:z53.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z53.string().min(1).optional(),model:z53.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=z53.object({jobId:z53.string(),status:z53.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z53.string().nullable().optional(),credits:z53.number().optional(),costUsd:z53.number().optional(),billingMode:z53.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z53.object({error:z53.string(),code:z53.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:z53.array(GenerationTaskIdSchema).optional(),availableModels:z53.array(z53.string()).optional(),issues:z53.array(z53.unknown()).optional()})}});import{z as z54}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=z54.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z54.object({name:z54.string(),key:z54.string(),description:z54.string(),type:FlagTypeSchema,required:z54.boolean(),defaultValue:z54.unknown().optional(),enumValues:z54.array(z54.string()).optional(),isArray:z54.boolean()}),AssetModelPriceSchema=z54.object({unitPrice:z54.number(),unit:z54.string(),confidence:z54.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z54.object({id:z54.string(),shortName:z54.string(),provider:z54.string(),source:z54.string(),modality:z54.enum(["image","video","audio"]),tags:z54.array(z54.string()),displayName:z54.string(),description:z54.string(),flags:z54.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z54.object({model:z54.string(),costUsd:z54.number(),credits:z54.number(),billingMode:z54.enum(["fimo-credits","provider-account"]),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z55}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=z55.object({tourId:z55.string(),version:z55.string(),status:z55.string(),completedAt:z55.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z55.array(UserTourDTOSchema))}});import{z as z56}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=z56.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z56.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z56.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z56.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z56.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z56.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z56.enum(["user","agent","system"]),SupportReportTagSchema=z56.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z56.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z56.object({organization:z56.object({id:z56.string().trim().min(1).max(255),name:z56.string().trim().max(240).optional()}),project:z56.object({id:z56.uuid(),name:z56.string().trim().max(240).optional(),createdAt:z56.coerce.date().optional()}).optional(),environment:z56.string().trim().max(255).optional(),clientVersion:z56.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z56.object({message:z56.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z56.string().trim().max(200).optional(),limit:z56.coerce.number().int().min(1).max(100).default(50),offset:z56.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z56.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z56.uuid().nullable().optional(),note:z56.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=z56.object({message:z56.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z56.object({kind:SupportReportLinkKindSchema,label:z56.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z56.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z56.object({kind:SupportReportActorKindSchema,id:z56.string().nullable(),name:z56.string().nullable()}),SupportReportLinkDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportLinkKindSchema,label:z56.string(),url:SupportReportHttpUrlSchema,externalId:z56.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportEventKindSchema,body:z56.string().nullable(),metadata:z56.record(z56.string(),z56.unknown()),actor:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z56.object({id:z56.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z56.array(z56.string()),source:SupportReportSourceSchema,message:z56.string(),reporter:z56.object({id:z56.string().nullable(),name:z56.string().nullable(),email:z56.string().nullable()}),organization:z56.object({id:z56.string().nullable(),name:z56.string()}),project:z56.object({id:z56.uuid().nullable(),name:z56.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z56.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z56.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z56.string().nullable(),deliveredAt:z56.coerce.date().nullable()}).nullable(),duplicateOfReportId:z56.uuid().nullable(),resolvedAt:z56.coerce.date().nullable(),createdAt:z56.coerce.date(),updatedAt:z56.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z56.string().nullable(),clientVersion:z56.string().nullable(),links:z56.array(SupportReportLinkDTOSchema),events:z56.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z56.object({reports:z56.array(SupportReportSummaryDTOSchema),total:z56.number().int().nonnegative(),statusCounts:z56.object({new:z56.number().int().nonnegative(),in_progress:z56.number().int().nonnegative(),waiting:z56.number().int().nonnegative(),resolved:z56.number().int().nonnegative(),duplicate:z56.number().int().nonnegative(),irrelevant:z56.number().int().nonnegative(),ignored:z56.number().int().nonnegative()}),limit:z56.number().int().positive(),offset:z56.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z56.object({id:z56.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z56.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z57}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=z57.iso.datetime({offset:!0}).pipe(z57.coerce.date()),OpsRecentChatInputSchema=z57.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z57.string().trim().min(1).max(255).optional(),limit:z57.coerce.number().int().min(1).max(200).default(100),cursor:z57.string().trim().min(1).max(2e3).optional(),slim:z57.boolean().default(!0),reason:z57.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=z57.object({id:z57.string(),messageId:z57.string(),env:z57.string(),versionId:z57.string().nullable(),userId:z57.string().nullable(),role:z57.string(),parts:z57.array(z57.record(z57.string(),z57.unknown())),metadata:z57.object({status:z57.string().optional(),traceUrl:z57.string().optional(),externalFileChanges:z57.array(z57.unknown()).optional()}),stats:z57.object({toolCount:z57.number().int().nonnegative(),failedToolCount:z57.number().int().nonnegative()}),createdAt:z57.iso.datetime({offset:!0}),project:z57.object({id:z57.string(),name:z57.string(),displayName:z57.string().nullable(),organizationId:z57.string().nullable()})}),OpsRecentChatResponseSchema=z57.object({target:z57.object({backendProfile:OpsBackendProfileSchema,projectEnv:z57.string().nullable()}),window:z57.object({from:z57.iso.datetime({offset:!0}),to:z57.iso.datetime({offset:!0})}),messages:z57.object({items:z57.array(OpsRecentChatMessageSchema),nextCursor:z57.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z58}from"zod";function createAgentRunWebhookEventDataSchema(status){return z58.object({run:z58.object({id:z58.string(),agentName:z58.string(),trigger:z58.string(),status:z58.literal(status),startedAt:z58.string().nullable(),finishedAt:z58.string().nullable(),reason:z58.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,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z58.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z58.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z58.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z58.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z58.union([z58.literal(0),z58.literal(5),z58.literal(30),z58.literal(60)]),EntryChangedWebhookEventDataSchema=z58.object({reason:WebhookEntryChangeReasonSchema,operationId:z58.string().optional(),batch:z58.object({index:z58.number().int().positive(),total:z58.number().int().positive()}).optional(),changes:z58.array(z58.object({action:WebhookEntryChangeActionSchema,contentType:z58.string(),id:z58.string(),documentId:z58.string(),locale:z58.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z58.object({form:z58.object({id:z58.string(),label:z58.string()}),submission:z58.object({id:z58.string(),data:z58.record(z58.string(),z58.unknown()),submittedAt:z58.string()})}),PublishStartedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("publishing"),startedAt:z58.string()})}),PublishSucceededWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("published"),url:z58.string(),publishedAt:z58.string(),firstPublish:z58.boolean()})}),PublishFailedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("failed"),reason:z58.string()})}),PublishUnpublishedWebhookEventDataSchema=z58.object({publication:z58.object({previousUrl:z58.string(),unpublishedAt:z58.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),classification:z58.string(),summary:z58.string(),reasons:z58.array(z58.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),resolution:z58.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z58.object({report:z58.object({weekStart:z58.string(),weekEnd:z58.string(),pageviews:z58.number(),visitors:z58.number(),previousPageviews:z58.number(),previousVisitors:z58.number()})}),MediaAssetWebhookEventDataSchema=z58.object({id:z58.string().nullable(),name:z58.string().nullable(),type:z58.string(),mimeType:z58.string().nullable(),fileSize:z58.number().nullable()}),MediaUploadedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["updated","moved","analysis"]),analysis:z58.object({category:z58.string(),status:z58.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("generated"),generation:z58.object({model:z58.string(),mode:z58.string()})}),MediaProcessingFailedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["analysis","generation"]),failure:z58.object({code:z58.string()})}),DomainCreatedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string()})}),LabelChangedWebhookEventDataSchema=z58.object({changes:z58.array(z58.object({action:z58.enum(["created","updated","deleted"]),key:z58.string(),locale:z58.string(),value:z58.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),isDefault:z58.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),previousCode:z58.string()})}),LocaleDeletedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z58.object({merge:z58.object({id:z58.string(),from:EnvSchema,to:EnvSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema}),version:z58.object({id:z58.string(),name:z58.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z58.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z58.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z58.discriminatedUnion("source",[z58.object({source:z58.literal("literal"),value:z58.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z58.object({source:z58.literal("secret"),key:z58.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z58.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z58.object({name:z58.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z58.object({name:z58.string(),source:z58.enum(["literal","secret"]),secretKey:z58.string().nullable(),secretPrefix:z58.string().nullable(),configured:z58.literal(!0)}),WebhookFilterSchema=z58.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z58.string().min(1).max(255).optional(),agentName:z58.string().min(1).max(120).optional(),mediaType:z58.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z58.string().min(1).max(255).optional(),locale:z58.string().min(1).max(120).optional()}),JsonValueSchema=z58.lazy(()=>z58.union([z58.string(),z58.number(),z58.boolean(),z58.null(),z58.array(JsonValueSchema),z58.record(z58.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z58.url(),enabled:z58.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z58.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z58.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z58.url().optional(),enabled:z58.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z58.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z58.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z58.object({eventType:WebhookEventTypeSchema.optional(),data:z58.record(z58.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z58.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z58.uuid(),name:z58.string(),eventType:WebhookEventTypeSchema,enabled:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z58.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z58.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z58.coerce.date().nullable(),deliveryStats24h:z58.object({succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z58.uuid(),projectId:z58.uuid(),env:EnvSchema,eventId:z58.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z58.number().int().positive(),test:z58.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z58.number().int().nonnegative(),responseStatus:z58.number().int().nullable(),lastErrorCode:z58.string().nullable(),lastErrorMessage:z58.string().nullable(),payloadAvailable:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z58.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z58.string().nullable(),qstashMessageId:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z58.object({items:z58.array(WebhookDeliveryDTOSchema),pagination:z58.object({page:z58.number().int().positive(),limit:z58.number().int().positive(),total:z58.number().int().nonnegative(),totalPages:z58.number().int().positive(),hasMore:z58.boolean()}),stats:z58.object({total:z58.number().int().nonnegative(),succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z58.object({id:z58.uuid(),deliveryId:z58.uuid(),attempt:z58.number().int().positive(),status:z58.enum(["delivering","succeeded","failed"]),responseStatus:z58.number().int().nullable(),durationMs:z58.number().int().nonnegative(),responseExcerpt:z58.string().nullable(),errorCode:z58.string().nullable(),errorMessage:z58.string().nullable(),createdAt:z58.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z58.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z58.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z59}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=z59.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z59.object({total:z59.number(),base:z59.number(),purchases:z59.number(),awards:z59.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z59.object({id:z59.string(),name:z59.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z59.object({type:z59.string(),brand:z59.string().nullable(),last4:z59.string().nullable(),expirationDate:z59.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z59.object({currency:z59.string(),nextPaymentAmount:z59.number().nullable(),nextPaymentAt:z59.string().nullable(),billingInterval:z59.string().nullable(),totalAmount:z59.number().nullable(),discountAmount:z59.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z59.object({id:z59.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z59.string().nullable(),currentPeriodEndsAt:z59.string().nullable(),renewsAt:z59.string().nullable(),cancelAt:z59.string().nullable(),renewAutomatically:z59.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z59.object({type:z59.enum(["low_balance","critical_balance","approaching_limit"]),message:z59.string(),estimatedPromptsRemaining:z59.number().nullable(),avgCostPerPrompt:z59.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z59.object({monthlyCredits:z59.number().nullable(),usedThisPeriod:z59.number(),remainingThisPeriod:z59.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z59.object({organizationId:z59.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z59.string().nullable(),tenureDays:z59.number().int().nonnegative(),capturedAt:z59.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z59.object({hasSubscription:z59.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z59.number().nullable(),alerts:z59.array(CreditAlertDTOSchema),portalUrl:z59.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z59.object({creditCount:z59.number().int().positive(),expiresAt:z59.string().datetime().nullable().optional(),message:z59.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("free"),amountCents:z59.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("purchase"),amountCents:z59.number().int().positive()}),CreditTopupRequestDTOSchema=z59.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z59.object({success:z59.boolean(),transactionId:z59.string().nullable(),newBalance:z59.number(),creditCount:z59.number(),type:z59.enum(["free","purchase"]),invoiceId:z59.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z60}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=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),periodStart:z60.string().nullable(),periodEnd:z60.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z60.array(UsageByUserForProjectDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z60.object({summary:UsageSummaryDTOSchema,byProject:z60.array(UsageByProjectDTOSchema),byUser:z60.array(UsageByUserDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z61}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=z61.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z61.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z61.object({startDate:z61.string().optional(),endDate:z61.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z61.coerce.number().int().positive().default(1),limit:z61.coerce.number().int().positive().max(100).default(20),sortBy:z61.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z61.string().optional()}),UsageOverviewSummaryDTOSchema=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),avgCreditsPerMessage:z61.number(),periodStart:z61.string(),periodEnd:z61.string(),creditsChange:z61.number().nullable(),costChange:z61.number().nullable(),messagesChange:z61.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z61.object({organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number(),projectCount:z61.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().nullable(),userImage:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),projectCount:z61.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z61.object({id:z61.string(),name:z61.string(),value:z61.number(),percentage:z61.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z61.object({day:z61.number(),hour:z61.number(),value:z61.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z61.object({summary:UsageOverviewSummaryDTOSchema,timeline:z61.array(UsageTimelinePointDTOSchema),topOrganizations:z61.array(OrganizationUsageRowDTOSchema),topUsers:z61.array(UserUsageRowDTOSchema),topProjects:z61.array(ProjectUsageRowDTOSchema),creditDistribution:z61.array(UsageDistributionItemDTOSchema),heatmap:z61.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z61.object({page:z61.number(),limit:z61.number(),totalItems:z61.number(),totalPages:z61.number(),hasMore:z61.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z61.object({organizations:z61.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z61.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z61.object({users:z61.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z61.object({projects:z61.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z61.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z61.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z61.object({credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),createdAt:z61.string(),memberCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z61.object({id:z61.string(),name:z61.string().nullable(),email:z61.string(),image:z61.string().nullable(),createdAt:z61.string(),organizationCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),displayName:z61.string().nullable(),createdAt:z61.string(),organizationId:z61.string(),organizationName:z61.string(),ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z62}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=z62.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z62.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z62.object({command:z62.string().min(1).max(1e4),cwd:z62.string().optional(),projectEnv:EnvSchema.optional(),env:z62.record(z62.string(),z62.string()).optional(),name:z62.string().optional(),waitForCompletion:z62.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z62.object({identifier:z62.string(),status:SandboxProcessStatusSchema,command:z62.string().optional(),startedAt:z62.string().optional(),exitCode:z62.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z62.object({processes:z62.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z62.object({processId:z62.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z62.object({success:z62.boolean(),message:z62.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z63}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_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_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 runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(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 runGit(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["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(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});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}}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});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
195
+ ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}return selected.has("windsurf")&&writeIfMissing(".windsurfrules",agentsMdContent),selected.has("gemini-cli")&&writeIfMissing("GEMINI.md",agentsMdContent),result}function syncPerAgentVariants(targetDir,agents){let agentsMdPath=path9.join(targetDir,"AGENTS.md");if(!fs9.existsSync(agentsMdPath))throw new Error(`No AGENTS.md found in ${targetDir}. Run \`fimo create\` first, or create AGENTS.md manually before running \`fimo rules sync\`.`);let agentsMdContent=fs9.readFileSync(agentsMdPath,"utf8");return writePerAgentVariants(targetDir,agents,agentsMdContent)}function detectAgentsInProject(cwd){let detected=[];return fs9.existsSync(path9.join(cwd,"CLAUDE.md"))&&detected.push("claude-code"),fs9.existsSync(path9.join(cwd,".cursor","rules","fimo.mdc"))&&detected.push("cursor"),fs9.existsSync(path9.join(cwd,".windsurfrules"))&&detected.push("windsurf"),fs9.existsSync(path9.join(cwd,"GEMINI.md"))&&detected.push("gemini-cli"),detected}var TEMPLATE_ROOT,AGENT_TEMPLATES_ROOT,EXCLUDED_DIRS,init_scaffold=__esm({"src/cli/utils/scaffold.ts"(){init_templates();init_config();init_templates();TEMPLATE_ROOT=getTemplatePath("react-router"),AGENT_TEMPLATES_ROOT=path9.resolve(CLI_ROOT,"assets","agent-templates"),EXCLUDED_DIRS=new Set(["node_modules","dist","build",".turbo",".git"]);__name(resolveTemplateRoot,"resolveTemplateRoot");__name(resolveAgentTemplatesRoot,"resolveAgentTemplatesRoot");__name(resolveAgentTemplate,"resolveAgentTemplate");__name(listAgentTemplates,"listAgentTemplates");__name(copyAgentTemplate,"copyAgentTemplate");__name(copyTemplate,"copyTemplate");__name(pinFimoDependency,"pinFimoDependency");__name(copyTree,"copyTree");__name(writePerAgentVariants,"writePerAgentVariants");__name(syncPerAgentVariants,"syncPerAgentVariants");__name(detectAgentsInProject,"detectAgentsInProject")}});import{z as z5}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z5.ZodOptional||schema instanceof z5.ZodNullable||schema instanceof z5.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z5.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z5.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 z5.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z5.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 z5.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 z5.ZodObject)return createObjectDTO(schema);if(schema instanceof z5.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 z6}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z6.object({data:dataSchema}),"createResponseSchema")}});import{z as z7}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z7.object({page:z7.coerce.number().int().positive().default(1),limit:z7.coerce.number().int().positive().max(100).default(20)})}});import{z as z8}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:z8.coerce.date(),positiveInt:z8.number().int().positive(),nonNegativeInt:z8.number().int().nonnegative()},BaseEntitySchema=z8.object({id:z8.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z8.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z8.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z8.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z8.enum(["public","private"]),ProjectStatusSchema=z8.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z8.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z8.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z8.enum(["owner","admin","member"]),AssetTypeSchema=z8.enum(["file","folder"]),TemplateCodeSchema=z8.enum(["Free","Premium"]),FieldTypeSchema=z8.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 z9}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=z9.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 z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path47){let conditionPath=[...path47,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path47)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","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=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops: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=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops: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=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)})}});import{z as z14}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:z14.string(),displayName:z14.string().nullable(),subdomain:z14.string().nullable().optional(),subdomainUpdatedAt:z14.date().nullable().optional(),organizationId:z14.string().nullable(),createdBy:z14.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z14.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z14.string(),thumbnailUrl:z14.string().nullable(),publishedThumbnailUrl:z14.string().nullable(),category:z14.string().nullable(),appUrl:z14.string().nullable(),lastPublishedAt:z14.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z14.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z14.object({id:z14.uuid(),name:z14.string(),displayName:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),visibility:ProjectVisibilitySchema,category:z14.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z14.object({id:z14.string(),name:z14.string(),avatar:z14.string().nullable(),color:z14.object({bg:z14.string(),text:z14.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z14.object({path:z14.string(),content:z14.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z14.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z14.object({id:z14.string(),messageId:z14.string(),versionId:z14.string().nullable(),role:ProjectChatMessageRole,parts:z14.array(z14.any()),createdAt:z14.coerce.date()}),MessageUserMetadataSchema=z14.object({id:z14.string(),name:z14.string().nullable().optional(),image:z14.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z14.object({shortTitle:z14.string().optional(),questions:z14.array(z14.object({header:z14.string(),question:z14.string(),answer:z14.string(),selectedLabels:z14.array(z14.string()),freeText:z14.string(),skipped:z14.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z14.number(),metadata:z14.object({user:MessageUserMetadataSchema,changeManifest:z14.array(z14.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z14.object({id:z14.uuid(),versionId:z14.string(),projectId:z14.uuid(),commitHash:z14.string(),name:z14.string(),description:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z14.object({content:z14.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z14.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z14.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z14.object({success:z14.boolean(),message:z14.string().optional()})),ProjectPublicationStateDTOSchema=z14.object({isPublished:z14.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z14.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z14.object({success:z14.boolean(),message:z14.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z15}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=z15.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z15.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z15.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z15.string().nullable(),deletedAt:z15.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z15.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z15.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z15.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z15.object({surface:z15.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z15.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z15.number().int().nonnegative(),conflictCount:z15.number().int().nonnegative()}),EnvDiffResultSchema=z15.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z15.coerce.date(),surfaces:z15.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z16}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=z16.object({success:z16.literal(!0),downloadUrl:z16.string(),expiresAt:z16.string(),fileSize:z16.number(),duration:z16.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z16.object({success:z16.literal(!0),projectId:z16.string(),projectName:z16.string(),displayName:z16.string(),projectUrl:z16.string(),duration:z16.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z16.object({contentTypes:z16.number(),entries:z16.number(),assets:z16.number(),translations:z16.number(),forms:z16.number(),codeFiles:z16.number(),assetFiles:z16.number()}),ImportPreviewSurfaceDTOSchema=z16.object({name:z16.string(),included:z16.boolean(),count:z16.number().optional(),note:z16.string().optional()}),ImportPreviewDTOSchema=z16.object({projectName:z16.string(),displayName:z16.string().nullable(),visibility:z16.string().nullable(),category:z16.string().nullable(),exportedAt:z16.string(),version:z16.string(),envScope:z16.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z16.array(ImportPreviewSurfaceDTOSchema),fileSize:z16.number(),fileName:z16.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z16.object({success:z16.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z17}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=z17.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z17.object({type:z17.literal("manual")}),ScheduleTriggerSchema=z17.object({type:z17.literal("schedule"),cron:z17.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:z17.string().optional()}),WebhookTriggerSchema2=z17.object({type:z17.literal("webhook"),path:z17.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z17.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z18}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=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z18.object({projectId:z18.uuid(),env:EnvSchema,agentName:z18.string().min(1),triggerIndex:z18.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z18.boolean(),lastFiredAt:z18.coerce.date().nullable(),webhookPath:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z18.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z18.object({error:z18.literal("webhook_path_taken"),conflictAgent:z18.string(),path:z18.string()}),ManualRunRequestSchema=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,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=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemActivationSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z20.string().min(1),active:z20.boolean()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),activations:z20.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}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=z21.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z21.object({cpuMs:z21.number().nonnegative().default(0),netBytes:z21.number().nonnegative().default(0),walltimeMs:z21.number().nonnegative().default(0),llmTokensIn:z21.number().nonnegative().optional(),llmTokensOut:z21.number().nonnegative().optional()}),AgentSessionDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),env:EnvSchema,agentName:z21.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z21.unknown().optional(),capabilities:z21.array(z21.string()).optional(),dataSources:z21.array(z21.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z21.string().nullable(),startedAt:z21.coerce.date().nullable(),finishedAt:z21.coerce.date().nullable(),cancelledAt:z21.coerce.date().nullable(),costUsd:z21.number().nonnegative(),costCeilingUsd:z21.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z21.boolean(),lastCheckpointId:z21.uuid().nullable(),branchEnvId:z21.uuid().nullable(),parentSessionId:z21.uuid().nullable(),terminalReason:z21.string().nullable(),errorMessage:z21.string().nullable(),report:z21.string().nullable(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z21.object({id:z21.uuid(),sessionId:z21.uuid(),checkpointIdx:z21.number().int().nonnegative(),payloadRef:z21.string(),payloadSizeBytes:z21.number().int().nonnegative(),checksum:z21.string().length(64),createdAt:z21.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z21.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z21.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z21.object({session:AgentSessionDTOSchema,checkpoints:z21.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z21.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z21.object({reason:z21.string().min(1).max(120).optional()})}});import{z as z22}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=z22.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z22.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z22.object({id:z22.uuid(),envId:z22.uuid(),sessionId:z22.uuid().nullable(),skillName:z22.string().min(1),classification:AgentBranchClassificationSchema,rationale:z22.string().nullable(),summary:z22.string().nullable(),surfaceDeltas:z22.record(z22.string(),z22.unknown()),createdAt:z22.coerce.date(),decidedAt:z22.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z22.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z22.object({path:z22.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z22.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z22.object({code:z22.literal("merge_conflict"),message:z22.string(),conflicts:z22.record(z22.string(),z22.number().int().nonnegative())})}});import{z as z23}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=z23.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z23.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z23.enum(["secret_text"]),IntegrationCredentialUsageSchema=z23.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z23.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z23.object({mode:IntegrationAuthModeSchema,label:z23.string().min(1),description:z23.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z23.object({id:z23.string().min(1),label:z23.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z23.boolean()}),IntegrationToolDefinitionDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),description:z23.string().min(1)}),IntegrationRecipeDTOSchema=z23.object({title:z23.string().min(1),description:z23.string().min(1),command:z23.string().min(1).optional()}),IntegrationInfoDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),summary:z23.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z23.array(IntegrationAuthModeDTOSchema),credentials:z23.array(IntegrationCredentialDefinitionDTOSchema),tools:z23.array(IntegrationToolDefinitionDTOSchema),recipes:z23.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),installed:z23.boolean(),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z23.string().nullable(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),installedAt:z23.coerce.date().nullable(),updatedAt:z23.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z23.string(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z23.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z23.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z23.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z23.object({value:z23.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z23.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z23.object({id:z23.uuid(),organizationId:z23.string().min(1),integrationKey:z23.string().min(1),alias:z23.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z23.string().min(1),externalAccountName:z23.string().nullable(),externalBotUserId:z23.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z23.array(z23.string()),connectedAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z23.object({alias:z23.string().min(1).max(120).optional(),token:z23.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z23.object({integrationKey:z23.string().min(1),connectUrl:z23.string().url(),expiresAt:z23.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z23.object({ref:z23.string().min(1),connectionAlias:z23.string().min(1).optional(),agentName:z23.string().min(1).max(160).nullable().optional(),force:z23.boolean().optional()}),ProjectChannelBindingDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),connectionId:z23.uuid(),externalWorkspaceId:z23.string().min(1),externalChannelId:z23.string().min(1),externalChannelName:z23.string().nullable(),agentName:z23.string().nullable(),enabled:z23.boolean(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z23.object({markdown:z23.boolean().optional(),summary:z23.boolean().optional(),links:z23.boolean().optional(),images:z23.boolean().optional(),html:z23.union([z23.literal("cleaned"),z23.literal("raw"),z23.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z23.object({url:z23.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z23.object({query:z23.string().min(1),maxResults:z23.number().int().positive().max(20).optional(),sources:z23.array(z23.enum(["web","news","images"])).min(1).max(3).optional(),categories:z23.array(z23.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z23.enum(["hour","day","week","month","year"]).optional(),location:z23.string().min(1).max(160).optional(),country:z23.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z23.object({url:z23.string().url(),search:z23.string().min(1).optional(),limit:z23.number().int().positive().max(200).optional(),includeSubdomains:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z23.object({url:z23.string().url(),limit:z23.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z23.object({text:z23.string().min(1).max(200).optional(),cron:z23.string().min(1).max(120).optional(),timezone:z23.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z23.object({type:z23.enum(["scrape","crawl"]).default("scrape"),urls:z23.array(z23.string().url()).min(1).max(50),scrapeOptions:z23.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z23.object({name:z23.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z23.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z23.string().min(1).max(2e3).optional(),judgeEnabled:z23.boolean().optional(),retentionDays:z23.number().int().min(1).max(365).optional(),notification:z23.object({email:z23.object({enabled:z23.boolean().default(!0),recipients:z23.array(z23.string().email()).min(1).max(20),includeDiffs:z23.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z23.object({monitorId:z23.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z23.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z23.object({connectionAlias:z23.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z23.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.list"),input:z23.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z23.object({provider:z23.string().min(1),providerCredits:z23.number().nonnegative().optional(),providerCostUsd:z23.number().nonnegative().optional(),requests:z23.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z23.object({credits:z23.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()}),FirecrawlSearchToolOutputSchema=z23.object({query:z23.string(),provider:z23.literal("firecrawl"),warning:z23.string().optional(),results:z23.array(z23.object({title:z23.string(),url:z23.string(),snippet:z23.string().optional(),content:z23.string().optional(),score:z23.number().optional(),publishedAt:z23.string().optional()}))}),FirecrawlMapToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),count:z23.number(),links:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),description:z23.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),total:z23.number(),pages:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()})),warning:z23.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z23.object({cron:z23.string().optional(),text:z23.string().optional(),timezone:z23.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z23.object({id:z23.string().optional(),urls:z23.array(z23.string()).optional(),scrapeOptions:z23.record(z23.string(),z23.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z23.object({id:z23.string(),name:z23.string(),status:z23.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z23.string().nullable().optional(),lastRunAt:z23.string().nullable().optional(),currentCheckId:z23.string().nullable().optional(),targets:z23.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z23.string().nullable().optional(),judgeEnabled:z23.boolean().optional(),estimatedCreditsPerMonth:z23.number().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z23.object({id:z23.string(),monitorId:z23.string(),scheduledFor:z23.string().nullable().optional(),startedAt:z23.string().nullable().optional(),finishedAt:z23.string().nullable().optional(),estimatedCredits:z23.number().optional(),reservedCredits:z23.number().optional(),actualCredits:z23.number().optional(),billingStatus:z23.string().nullable().optional(),summary:z23.object({totalPages:z23.number().optional(),same:z23.number().optional(),changed:z23.number().optional(),new:z23.number().optional(),removed:z23.number().optional(),error:z23.number().optional()}).passthrough().optional(),error:z23.string().nullable().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitors:z23.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),deleted:z23.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),checks:z23.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),check:FirecrawlMonitorCheckOutputSchema,next:z23.string().optional()}),FirecrawlToolKeySchema=z23.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z23.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z23.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z23.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z23.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z23.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 z24}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=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable(),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema))}});import{z as z25}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=z25.object({id:z25.uuid(),occurredAt:z25.coerce.date(),projectId:z25.uuid().nullable(),env:z25.string().nullable(),actor:z25.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z25.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z25.unknown().optional(),ipAddress:z25.string().nullable().optional(),userAgent:z25.string().nullable().optional(),error:z25.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z25.object({rows:z25.array(AuditLogRowDTOSchema),nextCursor:z25.string().nullable()})),AuditLogQuerySchema=z25.object({env:z25.string().optional(),action:AuditActionSchema.optional(),actor:z25.string().optional(),from:z25.coerce.date().optional(),to:z25.coerce.date().optional(),limit:z25.coerce.number().int().min(1).max(200).optional(),cursor:z25.string().optional()})}});import{z as z26}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z26.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({env:EnvSchema,vs:EnvSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),triggerKind:z26.string(),triggerSpec:z26.record(z26.string(),z26.unknown()),enabled:z26.boolean(),emailRecipients:z26.array(z26.string()).nullable(),qstashScheduleId:z26.string().nullable()}),ActivationDiffSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z26.enum(CONFLICT_KINDS),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:ConflictKindSchema.optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:EnvSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}from"zod";var 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=z27.object({surface:SurfaceNameSchema,key:z27.string(),label:z27.string()}),InlineSchema=z27.object({text:z27.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z27.discriminatedUnion("type",[z27.object({type:z27.literal("paragraph"),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("preview"),ref:DiffRefSchema,caption:z27.string().optional()}),z27.object({type:z27.literal("code"),code:z27.string(),lang:z27.string().optional(),caption:z27.string().optional()}),z27.object({type:z27.literal("risk"),level:z27.enum(["warning","error"]),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("list"),items:z27.array(z27.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z27.object({headline:z27.string(),blocks:z27.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z27.object({summary:EnvDiffSummarySchema,fingerprint:z27.string(),generatedAt:z27.coerce.date(),cached:z27.boolean().optional(),credits:z27.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z28}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=z28.object({date:z28.string(),visitors:z28.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z28.object({key:z28.string(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z28.object({path:z28.string(),pageName:z28.string().nullable().optional(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z28.object({preset:z28.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z28.string(),requestedTo:z28.string(),effectiveFrom:z28.string(),effectiveTo:z28.string(),isRetentionLimited:z28.boolean(),groupBy:z28.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z28.object({date:z28.string(),content:z28.string(),updatedAt:z28.string(),updatedByUserId:z28.string()}),ProjectPageviewAnalyticsDTOSchema=z28.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative(),bounceRate:z28.number().min(0).max(100),viewsPerVisit:z28.number().nonnegative(),averageVisitDurationSeconds:z28.number().nonnegative(),visitorsSeries:z28.array(ProjectDailyVisitorsDTOSchema),topPages:z28.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z28.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z29}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=z29.object({id:z29.string(),email:z29.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z29.coerce.date(),createdAt:z29.coerce.date(),inviterUserId:z29.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z29.object({id:z29.string(),token:z29.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z29.object({success:z29.boolean(),projectId:z29.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z30}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=z30.object({id:z30.string(),name:z30.string(),image:z30.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z30.object({count:z30.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z30.object({counts:z30.object({signed_up:z30.int(),activated:z30.int()}),credits:z30.object({total:z30.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z30.email(),emailVerified:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z31}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=z31.object({id:z31.string(),principalType:ProjectPrincipalTypeSchema,principalId:z31.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z31.coerce.date(),expiresAt:z31.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z31.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z31.record(z31.string(),z31.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z31.object({access:z31.array(ProjectAccessItemDTOSchema),invites:z31.array(ProjectInviteDTOSchema),organization:z31.object({name:z31.string().nullable(),logo:z31.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z31.object({success:z31.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z31.object({success:z31.boolean(),projectId:z31.uuid()}))}});import{z as z32}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=z32.object({publicationStatus:PublicationStatusSchema,appUrl:z32.string().nullable(),lastPublishedAt:z32.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z33}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=z33.object({url:z33.url(),expiresAt:z33.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z33.discriminatedUnion("source",[z33.object({source:z33.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z33.null()}),z33.object({source:z33.literal("dev"),artifact:z33.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z34}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:z34.string(),slug:z34.string().nullable(),logo:z34.string().nullable(),metadata:z34.record(z34.string(),z34.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),email:z34.email(),image:z34.string().nullable()}),OrganizationMemberDTOSchema=z34.object({id:z34.string(),userId:z34.string(),organizationId:z34.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z34.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z35}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=z35.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z35.object({reason:CancellationReasonCodeSchema,details:z35.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z35.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z35.object({included:z35.number().optional(),unitPrice:z35.number().optional(),dailyCap:z35.number().nullable().optional()}),EntitlementsDTOSchema=z35.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z35.object({retentionDays:z35.number().int().positive(),canUseExtendedDateRanges:z35.boolean()}).optional(),members:z35.object({canInvite:z35.boolean(),maxMembers:z35.number().int().positive().nullable()}).optional(),projects:z35.object({canCreatePrivateProjects:z35.boolean(),maxPrivateProjects:z35.number().int().positive().nullable()}).optional(),domains:z35.object({canUseCustomDomains:z35.boolean(),maxDomains:z35.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z35.object({id:z35.string(),external_id:z35.string(),customerId:z35.string(),planId:z35.string(),planCode:TemplateCodeSchema,currentPeriod:z35.object({start:z35.string(),end:z35.string().nullable()}),cancelAt:z35.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z35.string(),nextPaymentAt:z35.string().nullable(),baseAmount:z35.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z35.object({totalCap:z35.number(),dailyCap:z35.number(),usedTotal:z35.number()}),CreditBalanceDTOSchema=z35.object({total:z35.number(),base:z35.number(),dailyBase:z35.number(),purchases:z35.number(),awards:z35.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z35.object({total:z35.number(),nearLimit:z35.boolean(),canChat:z35.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z35.object({dailyFreeAvailable:z35.number(),monthlyAvailable:z35.number(),purchasedAvailable:z35.number(),awardedAvailable:z35.number()}),ProjectDailyCreditAllowanceDTOSchema=z35.object({periodCap:z35.number(),dailyGrant:z35.number(),usedThisPeriod:z35.number(),remainingThisPeriod:z35.number()}),ProjectCreditBalanceDTOSchema=z35.object({projectId:z35.uuid(),organizationId:z35.string(),balance:z35.object({totalAvailable:z35.number(),nearLimit:z35.boolean(),canUseAi:z35.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z35.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z35.object({invoiceId:z35.string(),newBalance:z35.int(),creditCount:z35.int(),amountUsd:z35.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z35.object({url:z35.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 z36}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=z36.object({brand:z36.string(),last4:z36.string(),exp:z36.string(),isDefault:z36.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z37}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z37.string().superRefine((path47,ctx)=>{let segments=path47.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=z37.object({type:z37.literal("renameField"),contentType:z37.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z37.object({enabled:z37.boolean()}).strict(),ContentTypeDTOSchema=z37.object({id:z37.string(),name:z37.string(),label:z37.string(),isSingleton:z37.boolean(),i18n:ContentTypeI18nSchema,fields:z37.record(z37.string(),FieldDefinitionSchema),createdAt:z37.string(),updatedAt:z37.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z37.object({contentTypes:z37.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z37.object({id:z37.string(),entryId:z37.string(),documentId:z37.string(),slug:z37.string(),locale:z37.string().optional(),createdAt:z37.string(),updatedAt:z37.string(),__fimo:z37.object({contentType:z37.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({limit:z37.number(),offset:z37.number(),total:z37.number(),hasMore:z37.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z37.object({contentType:z37.string(),count:z37.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z37.object({counts:z37.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z37.object({count:z37.number().int().nonnegative(),sourceLocale:z37.string(),targetLocale:z37.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z37.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z37.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z37.union([z37.string(),z37.number(),z37.boolean(),z37.null()]),entryWhereOperatorSchema=z37.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z37.array(entryWhereScalarSchema).optional(),$nin:z37.array(entryWhereScalarSchema).optional(),$contains:z37.string().optional(),$startsWith:z37.string().optional(),$null:z37.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z37.object({data:z37.record(z37.string(),z37.unknown()),locale:z37.string().min(1).optional(),documentId:z37.uuid().optional()}),entryIdsSchema=z37.array(z37.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z37.object({sql:z37.string().min(1)}),BulkCreateEntriesRequestSchema=z37.object({entries:z37.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z37.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z37.object({updates:z37.array(z37.object({id:z37.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,locale:z37.string().min(1).optional()}),z37.object({where:EntryWhereSchema,locale:z37.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z37.object({data:z37.array(z37.record(z37.string(),z37.unknown())),meta:z37.object({rowCount:z37.number().int().nonnegative(),truncated:z37.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({created:z37.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({updated:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({deleted:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z38}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z38.object({index:z38.number().int().nonnegative(),contentType:z38.string(),field:z38.string(),value:z38.string(),against:z38.enum(["stored","batch"]),ownerDocumentId:z38.uuid().optional(),ownerIndex:z38.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z38.object({code:z38.literal("unique_conflict"),message:z38.string(),conflicts:z38.array(UniqueConflictSchema),truncated:z38.boolean().optional()})}});import{z as z39}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z39.object({kind:z39.literal("unique_conflict"),contentType:z39.string(),field:z39.string(),value:z39.string(),documentCount:z39.number().int().positive(),documentIds:z39.array(z39.uuid()),documentIdsTruncated:z39.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z39.object({code:z39.literal("schema_transition_rejected"),message:z39.string(),issues:z39.array(SchemaTransitionIssueSchema),truncated:z39.boolean().optional()})}});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";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z51.object({translated:z51.number().int().nonnegative(),total:z51.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z51.object({locale:z51.string(),isDefault:z51.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z51.object({defaultLocale:z51.string(),routing:z51.object({strategy:z51.literal("path-prefix"),prefixDefaultLocale:z51.boolean()}),locales:z51.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z51.object({locale:z51.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z51.object({locale:z51.string().min(1).max(40)}),ProjectLocaleMutationSchema=z51.object({locale:z51.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z51.object({locale:z51.string(),entriesDeleted:z51.number().int().nonnegative(),labelsDeleted:z51.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z52}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=z52.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z52.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=z52.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z52.number(),credits:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z53}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=z53.object({options:z53.record(z53.string(),z53.unknown()),name:z53.string().optional(),parentId:z53.string().nullable().optional(),altText:z53.string().optional(),caption:z53.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z53.string().min(1).optional(),model:z53.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=z53.object({jobId:z53.string(),status:z53.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z53.string().nullable().optional(),credits:z53.number().optional(),costUsd:z53.number().optional(),billingMode:z53.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z53.object({error:z53.string(),code:z53.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:z53.array(GenerationTaskIdSchema).optional(),availableModels:z53.array(z53.string()).optional(),issues:z53.array(z53.unknown()).optional()})}});import{z as z54}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=z54.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z54.object({name:z54.string(),key:z54.string(),description:z54.string(),type:FlagTypeSchema,required:z54.boolean(),defaultValue:z54.unknown().optional(),enumValues:z54.array(z54.string()).optional(),isArray:z54.boolean()}),AssetModelPriceSchema=z54.object({unitPrice:z54.number(),unit:z54.string(),confidence:z54.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z54.object({id:z54.string(),shortName:z54.string(),provider:z54.string(),source:z54.string(),modality:z54.enum(["image","video","audio"]),tags:z54.array(z54.string()),displayName:z54.string(),description:z54.string(),flags:z54.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z54.object({model:z54.string(),costUsd:z54.number(),credits:z54.number(),billingMode:z54.enum(["fimo-credits","provider-account"]),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z55}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=z55.object({tourId:z55.string(),version:z55.string(),status:z55.string(),completedAt:z55.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z55.array(UserTourDTOSchema))}});import{z as z56}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=z56.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z56.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z56.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z56.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z56.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z56.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z56.enum(["user","agent","system"]),SupportReportTagSchema=z56.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z56.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z56.object({organization:z56.object({id:z56.string().trim().min(1).max(255),name:z56.string().trim().max(240).optional()}),project:z56.object({id:z56.uuid(),name:z56.string().trim().max(240).optional(),createdAt:z56.coerce.date().optional()}).optional(),environment:z56.string().trim().max(255).optional(),clientVersion:z56.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z56.object({message:z56.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z56.string().trim().max(200).optional(),limit:z56.coerce.number().int().min(1).max(100).default(50),offset:z56.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z56.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z56.uuid().nullable().optional(),note:z56.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=z56.object({message:z56.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z56.object({kind:SupportReportLinkKindSchema,label:z56.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z56.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z56.object({kind:SupportReportActorKindSchema,id:z56.string().nullable(),name:z56.string().nullable()}),SupportReportLinkDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportLinkKindSchema,label:z56.string(),url:SupportReportHttpUrlSchema,externalId:z56.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportEventKindSchema,body:z56.string().nullable(),metadata:z56.record(z56.string(),z56.unknown()),actor:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z56.object({id:z56.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z56.array(z56.string()),source:SupportReportSourceSchema,message:z56.string(),reporter:z56.object({id:z56.string().nullable(),name:z56.string().nullable(),email:z56.string().nullable()}),organization:z56.object({id:z56.string().nullable(),name:z56.string()}),project:z56.object({id:z56.uuid().nullable(),name:z56.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z56.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z56.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z56.string().nullable(),deliveredAt:z56.coerce.date().nullable()}).nullable(),duplicateOfReportId:z56.uuid().nullable(),resolvedAt:z56.coerce.date().nullable(),createdAt:z56.coerce.date(),updatedAt:z56.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z56.string().nullable(),clientVersion:z56.string().nullable(),links:z56.array(SupportReportLinkDTOSchema),events:z56.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z56.object({reports:z56.array(SupportReportSummaryDTOSchema),total:z56.number().int().nonnegative(),statusCounts:z56.object({new:z56.number().int().nonnegative(),in_progress:z56.number().int().nonnegative(),waiting:z56.number().int().nonnegative(),resolved:z56.number().int().nonnegative(),duplicate:z56.number().int().nonnegative(),irrelevant:z56.number().int().nonnegative(),ignored:z56.number().int().nonnegative()}),limit:z56.number().int().positive(),offset:z56.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z56.object({id:z56.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z56.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z57}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=z57.iso.datetime({offset:!0}).pipe(z57.coerce.date()),OpsRecentChatInputSchema=z57.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z57.string().trim().min(1).max(255).optional(),limit:z57.coerce.number().int().min(1).max(200).default(100),cursor:z57.string().trim().min(1).max(2e3).optional(),slim:z57.boolean().default(!0),reason:z57.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=z57.object({id:z57.string(),messageId:z57.string(),env:z57.string(),versionId:z57.string().nullable(),userId:z57.string().nullable(),role:z57.string(),parts:z57.array(z57.record(z57.string(),z57.unknown())),metadata:z57.object({status:z57.string().optional(),traceUrl:z57.string().optional(),externalFileChanges:z57.array(z57.unknown()).optional()}),stats:z57.object({toolCount:z57.number().int().nonnegative(),failedToolCount:z57.number().int().nonnegative()}),createdAt:z57.iso.datetime({offset:!0}),project:z57.object({id:z57.string(),name:z57.string(),displayName:z57.string().nullable(),organizationId:z57.string().nullable()})}),OpsRecentChatResponseSchema=z57.object({target:z57.object({backendProfile:OpsBackendProfileSchema,projectEnv:z57.string().nullable()}),window:z57.object({from:z57.iso.datetime({offset:!0}),to:z57.iso.datetime({offset:!0})}),messages:z57.object({items:z57.array(OpsRecentChatMessageSchema),nextCursor:z57.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z58}from"zod";function createAgentRunWebhookEventDataSchema(status){return z58.object({run:z58.object({id:z58.string(),agentName:z58.string(),trigger:z58.string(),status:z58.literal(status),startedAt:z58.string().nullable(),finishedAt:z58.string().nullable(),reason:z58.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,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z58.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z58.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z58.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z58.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z58.union([z58.literal(0),z58.literal(5),z58.literal(30),z58.literal(60)]),EntryChangedWebhookEventDataSchema=z58.object({reason:WebhookEntryChangeReasonSchema,operationId:z58.string().optional(),batch:z58.object({index:z58.number().int().positive(),total:z58.number().int().positive()}).optional(),changes:z58.array(z58.object({action:WebhookEntryChangeActionSchema,contentType:z58.string(),id:z58.string(),documentId:z58.string(),locale:z58.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z58.object({form:z58.object({id:z58.string(),label:z58.string()}),submission:z58.object({id:z58.string(),data:z58.record(z58.string(),z58.unknown()),submittedAt:z58.string()})}),PublishStartedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("publishing"),startedAt:z58.string()})}),PublishSucceededWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("published"),url:z58.string(),publishedAt:z58.string(),firstPublish:z58.boolean()})}),PublishFailedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("failed"),reason:z58.string()})}),PublishUnpublishedWebhookEventDataSchema=z58.object({publication:z58.object({previousUrl:z58.string(),unpublishedAt:z58.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),classification:z58.string(),summary:z58.string(),reasons:z58.array(z58.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),resolution:z58.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z58.object({report:z58.object({weekStart:z58.string(),weekEnd:z58.string(),pageviews:z58.number(),visitors:z58.number(),previousPageviews:z58.number(),previousVisitors:z58.number()})}),MediaAssetWebhookEventDataSchema=z58.object({id:z58.string().nullable(),name:z58.string().nullable(),type:z58.string(),mimeType:z58.string().nullable(),fileSize:z58.number().nullable()}),MediaUploadedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["updated","moved","analysis"]),analysis:z58.object({category:z58.string(),status:z58.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("generated"),generation:z58.object({model:z58.string(),mode:z58.string()})}),MediaProcessingFailedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["analysis","generation"]),failure:z58.object({code:z58.string()})}),DomainCreatedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string()})}),LabelChangedWebhookEventDataSchema=z58.object({changes:z58.array(z58.object({action:z58.enum(["created","updated","deleted"]),key:z58.string(),locale:z58.string(),value:z58.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),isDefault:z58.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),previousCode:z58.string()})}),LocaleDeletedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z58.object({merge:z58.object({id:z58.string(),from:EnvSchema,to:EnvSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema}),version:z58.object({id:z58.string(),name:z58.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z58.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z58.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z58.discriminatedUnion("source",[z58.object({source:z58.literal("literal"),value:z58.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z58.object({source:z58.literal("secret"),key:z58.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z58.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z58.object({name:z58.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z58.object({name:z58.string(),source:z58.enum(["literal","secret"]),secretKey:z58.string().nullable(),secretPrefix:z58.string().nullable(),configured:z58.literal(!0)}),WebhookFilterSchema=z58.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z58.string().min(1).max(255).optional(),agentName:z58.string().min(1).max(120).optional(),mediaType:z58.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z58.string().min(1).max(255).optional(),locale:z58.string().min(1).max(120).optional()}),JsonValueSchema=z58.lazy(()=>z58.union([z58.string(),z58.number(),z58.boolean(),z58.null(),z58.array(JsonValueSchema),z58.record(z58.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z58.url(),enabled:z58.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z58.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z58.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z58.url().optional(),enabled:z58.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z58.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z58.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z58.object({eventType:WebhookEventTypeSchema.optional(),data:z58.record(z58.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z58.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z58.uuid(),name:z58.string(),eventType:WebhookEventTypeSchema,enabled:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z58.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z58.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z58.coerce.date().nullable(),deliveryStats24h:z58.object({succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z58.uuid(),projectId:z58.uuid(),env:EnvSchema,eventId:z58.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z58.number().int().positive(),test:z58.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z58.number().int().nonnegative(),responseStatus:z58.number().int().nullable(),lastErrorCode:z58.string().nullable(),lastErrorMessage:z58.string().nullable(),payloadAvailable:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z58.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z58.string().nullable(),qstashMessageId:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z58.object({items:z58.array(WebhookDeliveryDTOSchema),pagination:z58.object({page:z58.number().int().positive(),limit:z58.number().int().positive(),total:z58.number().int().nonnegative(),totalPages:z58.number().int().positive(),hasMore:z58.boolean()}),stats:z58.object({total:z58.number().int().nonnegative(),succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z58.object({id:z58.uuid(),deliveryId:z58.uuid(),attempt:z58.number().int().positive(),status:z58.enum(["delivering","succeeded","failed"]),responseStatus:z58.number().int().nullable(),durationMs:z58.number().int().nonnegative(),responseExcerpt:z58.string().nullable(),errorCode:z58.string().nullable(),errorMessage:z58.string().nullable(),createdAt:z58.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z58.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z58.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z59}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=z59.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z59.object({total:z59.number(),base:z59.number(),purchases:z59.number(),awards:z59.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z59.object({id:z59.string(),name:z59.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z59.object({type:z59.string(),brand:z59.string().nullable(),last4:z59.string().nullable(),expirationDate:z59.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z59.object({currency:z59.string(),nextPaymentAmount:z59.number().nullable(),nextPaymentAt:z59.string().nullable(),billingInterval:z59.string().nullable(),totalAmount:z59.number().nullable(),discountAmount:z59.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z59.object({id:z59.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z59.string().nullable(),currentPeriodEndsAt:z59.string().nullable(),renewsAt:z59.string().nullable(),cancelAt:z59.string().nullable(),renewAutomatically:z59.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z59.object({type:z59.enum(["low_balance","critical_balance","approaching_limit"]),message:z59.string(),estimatedPromptsRemaining:z59.number().nullable(),avgCostPerPrompt:z59.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z59.object({monthlyCredits:z59.number().nullable(),usedThisPeriod:z59.number(),remainingThisPeriod:z59.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z59.object({organizationId:z59.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z59.string().nullable(),tenureDays:z59.number().int().nonnegative(),capturedAt:z59.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z59.object({hasSubscription:z59.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z59.number().nullable(),alerts:z59.array(CreditAlertDTOSchema),portalUrl:z59.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z59.object({creditCount:z59.number().int().positive(),expiresAt:z59.string().datetime().nullable().optional(),message:z59.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("free"),amountCents:z59.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("purchase"),amountCents:z59.number().int().positive()}),CreditTopupRequestDTOSchema=z59.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z59.object({success:z59.boolean(),transactionId:z59.string().nullable(),newBalance:z59.number(),creditCount:z59.number(),type:z59.enum(["free","purchase"]),invoiceId:z59.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z60}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=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),periodStart:z60.string().nullable(),periodEnd:z60.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z60.array(UsageByUserForProjectDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z60.object({summary:UsageSummaryDTOSchema,byProject:z60.array(UsageByProjectDTOSchema),byUser:z60.array(UsageByUserDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z61}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=z61.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z61.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z61.object({startDate:z61.string().optional(),endDate:z61.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z61.coerce.number().int().positive().default(1),limit:z61.coerce.number().int().positive().max(100).default(20),sortBy:z61.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z61.string().optional()}),UsageOverviewSummaryDTOSchema=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),avgCreditsPerMessage:z61.number(),periodStart:z61.string(),periodEnd:z61.string(),creditsChange:z61.number().nullable(),costChange:z61.number().nullable(),messagesChange:z61.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z61.object({organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number(),projectCount:z61.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().nullable(),userImage:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),projectCount:z61.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z61.object({id:z61.string(),name:z61.string(),value:z61.number(),percentage:z61.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z61.object({day:z61.number(),hour:z61.number(),value:z61.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z61.object({summary:UsageOverviewSummaryDTOSchema,timeline:z61.array(UsageTimelinePointDTOSchema),topOrganizations:z61.array(OrganizationUsageRowDTOSchema),topUsers:z61.array(UserUsageRowDTOSchema),topProjects:z61.array(ProjectUsageRowDTOSchema),creditDistribution:z61.array(UsageDistributionItemDTOSchema),heatmap:z61.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z61.object({page:z61.number(),limit:z61.number(),totalItems:z61.number(),totalPages:z61.number(),hasMore:z61.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z61.object({organizations:z61.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z61.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z61.object({users:z61.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z61.object({projects:z61.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z61.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z61.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z61.object({credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),createdAt:z61.string(),memberCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z61.object({id:z61.string(),name:z61.string().nullable(),email:z61.string(),image:z61.string().nullable(),createdAt:z61.string(),organizationCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),displayName:z61.string().nullable(),createdAt:z61.string(),organizationId:z61.string(),organizationName:z61.string(),ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z62}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=z62.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z62.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z62.object({command:z62.string().min(1).max(1e4),cwd:z62.string().optional(),projectEnv:EnvSchema.optional(),env:z62.record(z62.string(),z62.string()).optional(),name:z62.string().optional(),waitForCompletion:z62.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z62.object({identifier:z62.string(),status:SandboxProcessStatusSchema,command:z62.string().optional(),startedAt:z62.string().optional(),exitCode:z62.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z62.object({processes:z62.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z62.object({processId:z62.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z62.object({success:z62.boolean(),message:z62.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z63}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_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_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 runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(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 runGit(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["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(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});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}}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});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
196
196
  `)}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,api:baseApi.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(bootstrapProjectCommand,"bootstrapProjectCommand")}});var isAmbiguous,isFullWidth,isWide,init_utils=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/utils.js"(){isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide")}});var ANSI_RE,CONTROL_RE,TAB_RE,EMOJI_RE,LATIN_RE,MODIFIER_RE,NO_TRUNCATION,getStringTruncatedWidth,dist_default,init_dist2=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/index.js"(){init_utils();ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index2=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index2>=length&&index2>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index2);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index2>=length)break;if(LATIN_RE.lastIndex=index2,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index2,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index2,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index2,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index2,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index2,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index2,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index2,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=EMOJI_RE.lastIndex;continue}index2+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth}});var NO_TRUNCATION2,fastStringWidth,dist_default2,init_dist3=__esm({"../../node_modules/.pnpm/fast-string-width@1.1.0/node_modules/fast-string-width/dist/index.js"(){init_dist2();NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth}});function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map(line=>exec(line,columns,options)).join(`
197
197
  `)}var ESC,CSI,END_CODE,ANSI_ESCAPE_BELL,ANSI_CSI,ANSI_OSC,ANSI_SGR_TERMINATOR,ANSI_ESCAPE_LINK,GROUP_REGEX,getClosingCode,wrapAnsiCode,wrapAnsiHyperlink,wrapWord,stringVisibleTrimSpacesRight,exec,CRLF_OR_LF,init_main=__esm({"../../node_modules/.pnpm/fast-wrap-ansi@0.1.6/node_modules/fast-wrap-ansi/lib/main.js"(){init_dist3();ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last2=words.length;for(;last2&&!dist_default2(words[last2-1]);)last2--;return last2===words.length?string:words.slice(0,last2).join(" ")+words.slice(last2).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index2=0;index2<words.length;index2++){let word=words[index2];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index2!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
198
198
  `),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate)inSurrogate=character>="\uD800"&&character<="\uDBFF";else continue;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code2=Number.parseFloat(groups.code);escapeCode=code2===END_CODE?void 0:code2}else groups?.uri!==void 0&&(escapeUrl=groups.uri.length===0?void 0:groups.uri)}if(preString[i+1]===`
@@ -259,12 +259,12 @@ ${a}${o}
259
259
  ${c2}`:""}`}default:{let o=i?`${t("cyan",d2)} `:"",c2=i?t("cyan",E2):"";return`${s}${o}${u2}
260
260
  ${c2}
261
261
  `}}}}).prompt(),"Ot")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}var init_interactive=__esm({"src/cli/utils/interactive.ts"(){init_dist();__name(isInteractive,"isInteractive");__name(assertInteractive,"assertInteractive")}});import fs14 from"node:fs";import path17 from"node:path";function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiUrl}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl};writeIfChanged(path17.join(targetDir,".fimo.settings.json"),`${JSON.stringify(fimoJson,null,2)}
262
- `);let initialSiteName=project.displayName?.trim()||project.name,configPath=path17.join(targetDir,"fimo-config.json");if(fs14.existsSync(configPath))try{let original=fs14.readFileSync(configPath,"utf-8"),config=JSON.parse(original),seo=config.seo??{};(typeof seo.siteName=="string"?seo.siteName.trim():"")||(config.seo={...seo,siteName:initialSiteName},writeIfChanged(configPath,`${JSON.stringify(config,null,2)}
263
- `))}catch{}let envPath=path17.join(targetDir,".env"),envLine=`VITE_API_URL=${tenantApiUrl}`,existingEnv=fs14.existsSync(envPath)?fs14.readFileSync(envPath,"utf-8"):"";if(!existingEnv.split(`
262
+ `);let envPath=path17.join(targetDir,".env"),envLine=`VITE_API_URL=${tenantApiUrl}`,existingEnv=fs14.existsSync(envPath)?fs14.readFileSync(envPath,"utf-8"):"";if(!existingEnv.split(`
264
263
  `).some(line=>line.trim().startsWith("VITE_API_URL="))){let prefix=existingEnv.length===0||existingEnv.endsWith(`
265
264
  `)?"":`
266
265
  `;fs14.writeFileSync(envPath,`${existingEnv}${prefix}${envLine}
267
- `)}}function writeIfChanged(filePath,content2){fs14.existsSync(filePath)&&fs14.readFileSync(filePath,"utf-8")===content2||fs14.writeFileSync(filePath,content2)}var init_local_project_files=__esm({"src/cli/utils/local-project-files.ts"(){__name(writeLocalProjectFiles,"writeLocalProjectFiles");__name(writeIfChanged,"writeIfChanged")}});function slugifyName(input){return input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var init_slug=__esm({"src/cli/utils/slug.ts"(){__name(slugifyName,"slugifyName")}});import fs15 from"node:fs";import path18 from"node:path";function defaultDirectoryName(project){let source=project.displayName?.trim()||project.name||project.id;return slugifyName(source)||project.id}function explainCloneRemoteError(error){return error instanceof ApiRequestError&&error.status===403?"Only users with manage access to this project can clone it locally.":error instanceof ApiRequestError&&error.status===404?"Project or env not found.":error instanceof Error?error.message:String(error)}function chooseCloneEnv(envs,requestedEnv){return requestedEnv?envs.find(env=>env.env===requestedEnv)??null:envs.find(env=>env.env===DEFAULT_ENV)??envs[0]??null}function projectFallback(projectId){return{id:projectId,name:projectId,displayName:null,organizationId:null}}function isNotFound(error){return error instanceof ApiRequestError&&error.status===404}async function selectProjectId(args){let command=args.command??"clone";if(assertInteractive("Pass a project ID explicitly, e.g. `fimo clone <projectId>`.",command),!args.activeOrganizationId)return ui.error({command,code:"NO_ORGANIZATION_SPECIFIED",message:"No active organization set.",hint:"Run `fimo orgs switch`, or pass a project ID explicitly."}),null;let listSp=spinner("Loading projects"),projects2;try{projects2=await args.api.listProjects(args.activeOrganizationId),listSp.succeed("Projects loaded")}catch(error){return listSp.fail("Could not load projects"),ui.error({command,code:"PROJECT_LIST_FAILED",message:error instanceof Error?error.message:String(error)}),null}if(projects2.length===0)return ui.info({command,message:"No projects in the active organization yet."}),null;let selected=await _t({message:args.message??"Select a project to clone",options:projects2.map(project=>({value:project.id,label:project.displayName??project.name,hint:project.id}))});return q(selected)?(ui.info({command,message:"Cancelled."}),null):selected}function projectNotFound(projectId,apiUrl){return{ok:!1,code:"PROJECT_NOT_FOUND",message:`Project ${projectId} was not found on ${apiUrl}.`,hint:"Check `fimo projects list`, or set FIMO_API_URL to the backend that owns this project."}}async function resolveRemote(args){let{api,projectId,requestedEnv,apiUrl}=args,firstEnv=requestedEnv??DEFAULT_ENV;try{return{ok:!0,env:firstEnv,remote:await api.withEnv(firstEnv).getGitRemote(projectId,firstEnv)}}catch(firstError){if(requestedEnv||!isNotFound(firstError))throw firstError;let envs;try{envs=await api.listEnvs(projectId)}catch(listError){if(isNotFound(listError))return projectNotFound(projectId,apiUrl);throw firstError}let fallbackEnv=chooseCloneEnv(envs,void 0);if(!fallbackEnv)return{ok:!1,code:"NO_CLONEABLE_ENVS",message:"This project does not have any cloneable envs.",hint:"Create an env before cloning this project."};if(fallbackEnv.env===firstEnv)throw firstError;return{ok:!0,env:fallbackEnv.env,remote:await api.withEnv(fallbackEnv.env).getGitRemote(projectId,fallbackEnv.env)}}}async function cloneProject(args){let{api,cfg,projectId,dir,env:requestedEnv}=args,remoteSp=spinner("Checking access and fetching git remote"),remote,env;try{let resolved=await resolveRemote({api,projectId,requestedEnv,apiUrl:cfg.apiUrl});if(!resolved.ok)throw remoteSp.fail("Could not fetch git remote"),new CloneError(resolved.code,resolved.message,resolved.hint);({remote,env}=resolved),remoteSp.succeed(`Remote ready (branch ${remote.branch})`)}catch(error){throw error instanceof CloneError?error:(remoteSp.fail("Could not fetch git remote"),new CloneError(error instanceof ApiRequestError&&error.status===403?"PROJECT_MANAGE_REQUIRED":"CLONE_FAILED",explainCloneRemoteError(error)))}let project=projectFallback(projectId),projectSp=spinner("Loading project details");try{project=await api.getProject(projectId),projectSp.succeed(`Project loaded (${project.displayName??project.name})`)}catch{projectSp.succeed("Project metadata unavailable; using project ID locally")}let targetDir=path18.resolve(dir??defaultDirectoryName(project));if(fs15.existsSync(targetDir)&&fs15.readdirSync(targetDir).length>0){let name=path18.basename(targetDir);throw new CloneError("DIRECTORY_NOT_EMPTY",`The folder "${name}" already exists and isn't empty.`,`Pick a different directory (e.g. \`fimo clone ${projectId} <dir>\`), or empty "${name}" first.`)}let relativeTarget=path18.relative(process.cwd(),targetDir)||".";if(!await remoteHasBranch(remote.url,remote.branch))throw new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Run `fimo init --project-id <id>` to scaffold and push it, or `fimo deploy` from an existing checkout.",{project,remote,env,targetDir,relativeTarget});let cloneSp=spinner(`Cloning ${remote.branch} into ${targetDir}`);try{await cloneRepo({url:remote.url,branch:remote.branch,targetDir}),cloneSp.succeed("Repository cloned")}catch(error){throw cloneSp.fail("Git clone failed"),isMissingRemoteBranch(error)?new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Deploy the project once (`fimo deploy` from the source checkout, or from Fimo), then clone again."):new CloneError("GIT_CLONE_FAILED",error instanceof Error?error.message:String(error))}let linkSp=spinner("Linking local project");try{let{cleanUrl}=planRemoteConfig(remote.url);await runGit(["remote","set-url","origin",cleanUrl],targetDir).catch(()=>{}),await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiUrl:remote.tenantApiUrl}),linkSp.succeed("Local project linked")}catch(error){throw linkSp.fail("Local project link failed"),new CloneError("PROJECT_LINK_FAILED",error instanceof Error?error.message:String(error))}return{project,env,branch:remote.branch,targetDir,relativeTarget}}async function cloneCommand(projectIdArg,dirArg,options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),api=new FimoApiClient(cfg),projectId=projectIdArg??await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id});if(!projectId)return;currentMode().format==="pretty"&&mt(`Cloning Fimo project ${projectId}`);let result;try{result=await cloneProject({api,cfg,projectId,dir:dirArg,env:options.env})}catch(error){if(error instanceof CloneError){ui.error({command:"clone",code:error.code,message:error.message,hint:error.hint});return}throw error}let{project,env,branch,targetDir,relativeTarget}=result;ui.ok({command:"clone",headline:`Project ${project.displayName??project.name} cloned.`,details:{project_id:project.id,project_name:project.name,display_name:project.displayName,organization_id:project.organizationId,env,branch,target_dir:targetDir,relative_dir:relativeTarget},hint:`cd ${relativeTarget}`})}var CloneError,init_clone=__esm({"src/cli/commands/clone.ts"(){init_dist5();init_esm();init_dist();init_api();init_auth();init_config();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_slug();CloneError=class extends Error{static{__name(this,"CloneError")}code;hint;emptyRemote;constructor(code2,message,hint,emptyRemote){super(message),this.name="CloneError",this.code=code2,this.hint=hint,this.emptyRemote=emptyRemote}};__name(defaultDirectoryName,"defaultDirectoryName");__name(explainCloneRemoteError,"explainCloneRemoteError");__name(chooseCloneEnv,"chooseCloneEnv");__name(projectFallback,"projectFallback");__name(isNotFound,"isNotFound");__name(selectProjectId,"selectProjectId");__name(projectNotFound,"projectNotFound");__name(resolveRemote,"resolveRemote");__name(cloneProject,"cloneProject");__name(cloneCommand,"cloneCommand")}});function split(value){let result=value.trim();result=result.replace(SPLIT_LOWER_UPPER_RE,SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE,SPLIT_REPLACE_VALUE),result=result.replace(DEFAULT_STRIP_REGEXP,"\0");let start=0,end2=result.length;for(;result.charAt(start)==="\0";)start++;if(start===end2)return[];for(;result.charAt(end2-1)==="\0";)end2--;return result.slice(start,end2).split(/\0/g)}function splitSeparateNumbers(value){let words=split(value);for(let i=0;i<words.length;i++){let word=words[i],match=SPLIT_SEPARATE_NUMBER_RE.exec(word);if(match){let offset=match.index+(match[1]??match[2]).length;words.splice(i,1,word.slice(0,offset),word.slice(offset))}}return words}function pascalCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map(transform).join(options?.delimiter??"")+suffix}function lowerFactory(locale){return locale===!1?input=>input.toLowerCase():input=>input.toLocaleLowerCase(locale)}function upperFactory(locale){return locale===!1?input=>input.toUpperCase():input=>input.toLocaleUpperCase(locale)}function capitalCaseTransformFactory(lower,upper){return word=>`${upper(word[0])}${lower(word.slice(1))}`}function pascalCaseTransformFactory(lower,upper){return(word,index2)=>{let char0=word[0];return(index2>0&&char0>="0"&&char0<="9"?"_"+char0:upper(char0))+lower(word.slice(1))}}function splitPrefixSuffix(input,options={}){let splitFn=options.split??(options.separateNumbers?splitSeparateNumbers:split),prefixCharacters=options.prefixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,suffixCharacters=options.suffixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,prefixIndex=0,suffixIndex=input.length;for(;prefixIndex<input.length;){let char=input.charAt(prefixIndex);if(!prefixCharacters.includes(char))break;prefixIndex++}for(;suffixIndex>prefixIndex;){let index2=suffixIndex-1,char=input.charAt(index2);if(!suffixCharacters.includes(char))break;suffixIndex=index2}return[input.slice(0,prefixIndex),splitFn(input.slice(prefixIndex,suffixIndex)),input.slice(suffixIndex)]}var SPLIT_LOWER_UPPER_RE,SPLIT_UPPER_UPPER_RE,SPLIT_SEPARATE_NUMBER_RE,DEFAULT_STRIP_REGEXP,SPLIT_REPLACE_VALUE,DEFAULT_PREFIX_SUFFIX_CHARACTERS,init_dist6=__esm({"../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js"(){SPLIT_LOWER_UPPER_RE=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),SPLIT_UPPER_UPPER_RE=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),SPLIT_SEPARATE_NUMBER_RE=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),DEFAULT_STRIP_REGEXP=/[^\p{L}\d]+/giu,SPLIT_REPLACE_VALUE="$1\0$2",DEFAULT_PREFIX_SUFFIX_CHARACTERS="";__name(split,"split");__name(splitSeparateNumbers,"splitSeparateNumbers");__name(pascalCase,"pascalCase");__name(lowerFactory,"lowerFactory");__name(upperFactory,"upperFactory");__name(capitalCaseTransformFactory,"capitalCaseTransformFactory");__name(pascalCaseTransformFactory,"pascalCaseTransformFactory");__name(splitPrefixSuffix,"splitPrefixSuffix")}});import*as path20 from"node:path";import*as fs17 from"node:fs";function ParseErr(message,str,indx){let whitespace2=str.slice(0,indx).split(/\n/),lineNo=whitespace2.length,colNo=whitespace2[lineNo-1].length+1;throw message+=" at line "+lineNo+" col "+colNo+`:
266
+ `)}}function seedSiteName(args){let{targetDir,project}=args,configPath=path17.join(targetDir,"fimo-config.json");if(fs14.existsSync(configPath))try{let original=fs14.readFileSync(configPath,"utf-8"),config=JSON.parse(original),seo=config.seo??{},existingName=typeof seo.siteName=="string"?seo.siteName:"";if(!existingName.trim()||existingName===STARTER_SITE_NAME){let initialSiteName=project.displayName?.trim()||project.name;config.seo={...seo,siteName:initialSiteName},writeIfChanged(configPath,`${JSON.stringify(config,null,2)}
267
+ `)}}catch{}}function writeIfChanged(filePath,content2){fs14.existsSync(filePath)&&fs14.readFileSync(filePath,"utf-8")===content2||fs14.writeFileSync(filePath,content2)}var STARTER_SITE_NAME,init_local_project_files=__esm({"src/cli/utils/local-project-files.ts"(){STARTER_SITE_NAME="Fimo Starter Site";__name(writeLocalProjectFiles,"writeLocalProjectFiles");__name(seedSiteName,"seedSiteName");__name(writeIfChanged,"writeIfChanged")}});function slugifyName(input){return input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var init_slug=__esm({"src/cli/utils/slug.ts"(){__name(slugifyName,"slugifyName")}});import fs15 from"node:fs";import path18 from"node:path";function defaultDirectoryName(project){let source=project.displayName?.trim()||project.name||project.id;return slugifyName(source)||project.id}function explainCloneRemoteError(error){return error instanceof ApiRequestError&&error.status===403?"Only users with manage access to this project can clone it locally.":error instanceof ApiRequestError&&error.status===404?"Project or env not found.":error instanceof Error?error.message:String(error)}function chooseCloneEnv(envs,requestedEnv){return requestedEnv?envs.find(env=>env.env===requestedEnv)??null:envs.find(env=>env.env===DEFAULT_ENV)??envs[0]??null}function projectFallback(projectId){return{id:projectId,name:projectId,displayName:null,organizationId:null}}function isNotFound(error){return error instanceof ApiRequestError&&error.status===404}async function selectProjectId(args){let command=args.command??"clone";if(assertInteractive("Pass a project ID explicitly, e.g. `fimo clone <projectId>`.",command),!args.activeOrganizationId)return ui.error({command,code:"NO_ORGANIZATION_SPECIFIED",message:"No active organization set.",hint:"Run `fimo orgs switch`, or pass a project ID explicitly."}),null;let listSp=spinner("Loading projects"),projects2;try{projects2=await args.api.listProjects(args.activeOrganizationId),listSp.succeed("Projects loaded")}catch(error){return listSp.fail("Could not load projects"),ui.error({command,code:"PROJECT_LIST_FAILED",message:error instanceof Error?error.message:String(error)}),null}if(projects2.length===0)return ui.info({command,message:"No projects in the active organization yet."}),null;let selected=await _t({message:args.message??"Select a project to clone",options:projects2.map(project=>({value:project.id,label:project.displayName??project.name,hint:project.id}))});return q(selected)?(ui.info({command,message:"Cancelled."}),null):selected}function projectNotFound(projectId,apiUrl){return{ok:!1,code:"PROJECT_NOT_FOUND",message:`Project ${projectId} was not found on ${apiUrl}.`,hint:"Check `fimo projects list`, or set FIMO_API_URL to the backend that owns this project."}}async function resolveRemote(args){let{api,projectId,requestedEnv,apiUrl}=args,firstEnv=requestedEnv??DEFAULT_ENV;try{return{ok:!0,env:firstEnv,remote:await api.withEnv(firstEnv).getGitRemote(projectId,firstEnv)}}catch(firstError){if(requestedEnv||!isNotFound(firstError))throw firstError;let envs;try{envs=await api.listEnvs(projectId)}catch(listError){if(isNotFound(listError))return projectNotFound(projectId,apiUrl);throw firstError}let fallbackEnv=chooseCloneEnv(envs,void 0);if(!fallbackEnv)return{ok:!1,code:"NO_CLONEABLE_ENVS",message:"This project does not have any cloneable envs.",hint:"Create an env before cloning this project."};if(fallbackEnv.env===firstEnv)throw firstError;return{ok:!0,env:fallbackEnv.env,remote:await api.withEnv(fallbackEnv.env).getGitRemote(projectId,fallbackEnv.env)}}}async function cloneProject(args){let{api,cfg,projectId,dir,env:requestedEnv}=args,remoteSp=spinner("Checking access and fetching git remote"),remote,env;try{let resolved=await resolveRemote({api,projectId,requestedEnv,apiUrl:cfg.apiUrl});if(!resolved.ok)throw remoteSp.fail("Could not fetch git remote"),new CloneError(resolved.code,resolved.message,resolved.hint);({remote,env}=resolved),remoteSp.succeed(`Remote ready (branch ${remote.branch})`)}catch(error){throw error instanceof CloneError?error:(remoteSp.fail("Could not fetch git remote"),new CloneError(error instanceof ApiRequestError&&error.status===403?"PROJECT_MANAGE_REQUIRED":"CLONE_FAILED",explainCloneRemoteError(error)))}let project=projectFallback(projectId),projectSp=spinner("Loading project details");try{project=await api.getProject(projectId),projectSp.succeed(`Project loaded (${project.displayName??project.name})`)}catch{projectSp.succeed("Project metadata unavailable; using project ID locally")}let targetDir=path18.resolve(dir??defaultDirectoryName(project));if(fs15.existsSync(targetDir)&&fs15.readdirSync(targetDir).length>0){let name=path18.basename(targetDir);throw new CloneError("DIRECTORY_NOT_EMPTY",`The folder "${name}" already exists and isn't empty.`,`Pick a different directory (e.g. \`fimo clone ${projectId} <dir>\`), or empty "${name}" first.`)}let relativeTarget=path18.relative(process.cwd(),targetDir)||".";if(!await remoteHasBranch(remote.url,remote.branch))throw new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Run `fimo init --project-id <id>` to scaffold and push it, or `fimo deploy` from an existing checkout.",{project,remote,env,targetDir,relativeTarget});let cloneSp=spinner(`Cloning ${remote.branch} into ${targetDir}`);try{await cloneRepo({url:remote.url,branch:remote.branch,targetDir}),cloneSp.succeed("Repository cloned")}catch(error){throw cloneSp.fail("Git clone failed"),isMissingRemoteBranch(error)?new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Deploy the project once (`fimo deploy` from the source checkout, or from Fimo), then clone again."):new CloneError("GIT_CLONE_FAILED",error instanceof Error?error.message:String(error))}let linkSp=spinner("Linking local project");try{let{cleanUrl}=planRemoteConfig(remote.url);await runGit(["remote","set-url","origin",cleanUrl],targetDir).catch(()=>{}),await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiUrl:remote.tenantApiUrl}),linkSp.succeed("Local project linked")}catch(error){throw linkSp.fail("Local project link failed"),new CloneError("PROJECT_LINK_FAILED",error instanceof Error?error.message:String(error))}return{project,env,branch:remote.branch,targetDir,relativeTarget}}async function cloneCommand(projectIdArg,dirArg,options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),api=new FimoApiClient(cfg),projectId=projectIdArg??await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id});if(!projectId)return;currentMode().format==="pretty"&&mt(`Cloning Fimo project ${projectId}`);let result;try{result=await cloneProject({api,cfg,projectId,dir:dirArg,env:options.env})}catch(error){if(error instanceof CloneError){ui.error({command:"clone",code:error.code,message:error.message,hint:error.hint});return}throw error}let{project,env,branch,targetDir,relativeTarget}=result;ui.ok({command:"clone",headline:`Project ${project.displayName??project.name} cloned.`,details:{project_id:project.id,project_name:project.name,display_name:project.displayName,organization_id:project.organizationId,env,branch,target_dir:targetDir,relative_dir:relativeTarget},hint:`cd ${relativeTarget}`})}var CloneError,init_clone=__esm({"src/cli/commands/clone.ts"(){init_dist5();init_esm();init_dist();init_api();init_auth();init_config();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_slug();CloneError=class extends Error{static{__name(this,"CloneError")}code;hint;emptyRemote;constructor(code2,message,hint,emptyRemote){super(message),this.name="CloneError",this.code=code2,this.hint=hint,this.emptyRemote=emptyRemote}};__name(defaultDirectoryName,"defaultDirectoryName");__name(explainCloneRemoteError,"explainCloneRemoteError");__name(chooseCloneEnv,"chooseCloneEnv");__name(projectFallback,"projectFallback");__name(isNotFound,"isNotFound");__name(selectProjectId,"selectProjectId");__name(projectNotFound,"projectNotFound");__name(resolveRemote,"resolveRemote");__name(cloneProject,"cloneProject");__name(cloneCommand,"cloneCommand")}});function split(value){let result=value.trim();result=result.replace(SPLIT_LOWER_UPPER_RE,SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE,SPLIT_REPLACE_VALUE),result=result.replace(DEFAULT_STRIP_REGEXP,"\0");let start=0,end2=result.length;for(;result.charAt(start)==="\0";)start++;if(start===end2)return[];for(;result.charAt(end2-1)==="\0";)end2--;return result.slice(start,end2).split(/\0/g)}function splitSeparateNumbers(value){let words=split(value);for(let i=0;i<words.length;i++){let word=words[i],match=SPLIT_SEPARATE_NUMBER_RE.exec(word);if(match){let offset=match.index+(match[1]??match[2]).length;words.splice(i,1,word.slice(0,offset),word.slice(offset))}}return words}function pascalCase(input,options){let[prefix,words,suffix]=splitPrefixSuffix(input,options),lower=lowerFactory(options?.locale),upper=upperFactory(options?.locale),transform=options?.mergeAmbiguousCharacters?capitalCaseTransformFactory(lower,upper):pascalCaseTransformFactory(lower,upper);return prefix+words.map(transform).join(options?.delimiter??"")+suffix}function lowerFactory(locale){return locale===!1?input=>input.toLowerCase():input=>input.toLocaleLowerCase(locale)}function upperFactory(locale){return locale===!1?input=>input.toUpperCase():input=>input.toLocaleUpperCase(locale)}function capitalCaseTransformFactory(lower,upper){return word=>`${upper(word[0])}${lower(word.slice(1))}`}function pascalCaseTransformFactory(lower,upper){return(word,index2)=>{let char0=word[0];return(index2>0&&char0>="0"&&char0<="9"?"_"+char0:upper(char0))+lower(word.slice(1))}}function splitPrefixSuffix(input,options={}){let splitFn=options.split??(options.separateNumbers?splitSeparateNumbers:split),prefixCharacters=options.prefixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,suffixCharacters=options.suffixCharacters??DEFAULT_PREFIX_SUFFIX_CHARACTERS,prefixIndex=0,suffixIndex=input.length;for(;prefixIndex<input.length;){let char=input.charAt(prefixIndex);if(!prefixCharacters.includes(char))break;prefixIndex++}for(;suffixIndex>prefixIndex;){let index2=suffixIndex-1,char=input.charAt(index2);if(!suffixCharacters.includes(char))break;suffixIndex=index2}return[input.slice(0,prefixIndex),splitFn(input.slice(prefixIndex,suffixIndex)),input.slice(suffixIndex)]}var SPLIT_LOWER_UPPER_RE,SPLIT_UPPER_UPPER_RE,SPLIT_SEPARATE_NUMBER_RE,DEFAULT_STRIP_REGEXP,SPLIT_REPLACE_VALUE,DEFAULT_PREFIX_SUFFIX_CHARACTERS,init_dist6=__esm({"../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js"(){SPLIT_LOWER_UPPER_RE=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),SPLIT_UPPER_UPPER_RE=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),SPLIT_SEPARATE_NUMBER_RE=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),DEFAULT_STRIP_REGEXP=/[^\p{L}\d]+/giu,SPLIT_REPLACE_VALUE="$1\0$2",DEFAULT_PREFIX_SUFFIX_CHARACTERS="";__name(split,"split");__name(splitSeparateNumbers,"splitSeparateNumbers");__name(pascalCase,"pascalCase");__name(lowerFactory,"lowerFactory");__name(upperFactory,"upperFactory");__name(capitalCaseTransformFactory,"capitalCaseTransformFactory");__name(pascalCaseTransformFactory,"pascalCaseTransformFactory");__name(splitPrefixSuffix,"splitPrefixSuffix")}});import*as path20 from"node:path";import*as fs17 from"node:fs";function ParseErr(message,str,indx){let whitespace2=str.slice(0,indx).split(/\n/),lineNo=whitespace2.length,colNo=whitespace2[lineNo-1].length+1;throw message+=" at line "+lineNo+" col "+colNo+`:
268
268
 
269
269
  `+str.split(/\n/)[lineNo-1]+`
270
270
  `+Array(colNo).join(" ")+"^",new EtaParseError(message)}function RuntimeErr(originalError,str,lineNo,path47){let lines=str.split(`
@@ -593,7 +593,7 @@ ${removed.map(r=>` ${r.skill} \u2192 ${r.agent}`).join(`
593
593
  `)}`,"render")})}function listReferenceDocs(skillDir){let refsDir=path31.join(skillDir,"references");if(!fs31.existsSync(refsDir))return[];let out=[],walk=__name((cur,prefix)=>{for(let entry of fs31.readdirSync(cur,{withFileTypes:!0})){let rel=prefix?`${prefix}/${entry.name}`:entry.name;entry.isDirectory()?walk(path31.join(cur,entry.name),rel):entry.isFile()&&entry.name.endsWith(".md")&&out.push(rel.slice(0,-3))}},"walk");return walk(refsDir,""),out.sort()}function discoverBundledSkills(){if(!fs31.existsSync(SKILLS_ROOT))return[];let skills2=[];for(let entry of fs31.readdirSync(SKILLS_ROOT,{withFileTypes:!0})){if(!entry.isDirectory()||entry.name===BOOTSTRAP_SKILL_NAME)continue;let dir=path31.join(SKILLS_ROOT,entry.name),skillMd=path31.join(dir,"SKILL.md");if(!fs31.existsSync(skillMd))continue;let{data:data2}=parseFrontmatter(fs31.readFileSync(skillMd,"utf8")),description=typeof data2.description=="string"?data2.description.trim():"";skills2.push({name:entry.name,description,refs:listReferenceDocs(dir),dir})}return skills2.sort((a,b)=>a.name.localeCompare(b.name))}function firstLine(text3){let line=text3.split(`
594
594
  `,1)[0]?.trim()??"";return line.length>80?`${line.slice(0,79)}\u2026`:line}function skillsListCommand(){let skills2=discoverBundledSkills();if(skills2.length===0){ui.error({command:"skills list",code:"BUNDLED_SKILL_MISSING",message:`No bundled skills found at ${SKILLS_ROOT}.`,hint:"Try reinstalling fimo, or report this as a bug."});return}ui.result({command:"skills list",data:{skills:skills2.map(s=>({name:s.name,description:s.description,refs:s.refs}))},render:__name(()=>{let nameWidth=Math.max(4,...skills2.map(s=>s.name.length)),header=`${"NAME".padEnd(nameWidth)} REFS DESCRIPTION`,lines=skills2.map(s=>{let refs=String(s.refs.length).padStart(4);return`${s.name.padEnd(nameWidth)} ${refs} ${firstLine(s.description)}`});return[header,...lines].join(`
595
595
  `)},"render"),hint:"Run `fimo skills get <name>` for a skill, or add `--ref <doc>` for a reference."})}function normalizeRef(ref){return ref.trim().replace(/\\/g,"/").replace(/^references\//,"").replace(/\.md$/,"")}function skillsGetCommand(name,options={}){let skills2=discoverBundledSkills(),skill=skills2.find(s=>s.name===name);if(!skill){ui.error({command:"skills get",code:"SKILL_NOT_FOUND",message:`Unknown skill "${name}".`,hint:skills2.length?`Available: ${skills2.map(s=>s.name).join(", ")}. Run \`fimo skills list\`.`:"No bundled skills found \u2014 try reinstalling fimo."});return}let targetPath,refId=null;if(options.ref){refId=normalizeRef(options.ref);let refsRoot=path31.resolve(skill.dir,"references"),candidate=path31.resolve(refsRoot,`${refId}.md`);if(!(candidate===refsRoot||candidate.startsWith(refsRoot+path31.sep))||!fs31.existsSync(candidate)){ui.error({command:"skills get",code:"SKILL_REF_NOT_FOUND",message:`Reference "${options.ref}" not found in skill "${skill.name}".`,hint:skill.refs.length?`Available refs: ${skill.refs.join(", ")}.`:"This skill has no reference docs."});return}targetPath=candidate}else targetPath=path31.join(skill.dir,"SKILL.md");let content2=fs31.readFileSync(targetPath,"utf8");ui.result({command:"skills get",data:{skill:skill.name,ref:refId,path:targetPath,content:content2},render:__name(()=>content2,"render")})}var SKILLS_ROOT,BOOTSTRAP_SKILL_NAME,BOOTSTRAP_SKILL_SOURCE,STALE_GLOBAL_SKILL_NAMES,DETECTABLE_FIMO_SKILL_NAMES,init_skills=__esm({"src/cli/commands/skills.ts"(){init_dist5();init_dist();init_dist7();init_config();init_agents();SKILLS_ROOT=path31.resolve(CLI_ROOT,"assets","skills"),BOOTSTRAP_SKILL_NAME="fimo",BOOTSTRAP_SKILL_SOURCE=path31.join(SKILLS_ROOT,BOOTSTRAP_SKILL_NAME),STALE_GLOBAL_SKILL_NAMES=["fimo-cli","fimo-studio","fimo-migration","fimo-migrate","fimo-source-migrate"],DETECTABLE_FIMO_SKILL_NAMES=[BOOTSTRAP_SKILL_NAME,...STALE_GLOBAL_SKILL_NAMES];__name(isPrettyMode,"isPrettyMode");__name(runSkillsInstall,"runSkillsInstall");__name(renderSkillsInstall,"renderSkillsInstall");__name(skillsInstallCommand,"skillsInstallCommand");__name(skillsSyncCommand,"skillsSyncCommand");__name(detectAgentsWithFimoSkills,"detectAgentsWithFimoSkills");__name(removeDirIfExists,"removeDirIfExists");__name(removeGlobalSkillDirs,"removeGlobalSkillDirs");__name(hasGlobalSkillInstalled,"hasGlobalSkillInstalled");__name(removeCanonicalSkillDirs,"removeCanonicalSkillDirs");__name(cleanupStaleGlobalSkills,"cleanupStaleGlobalSkills");__name(skillsUninstallCommand,"skillsUninstallCommand");__name(listReferenceDocs,"listReferenceDocs");__name(discoverBundledSkills,"discoverBundledSkills");__name(firstLine,"firstLine");__name(skillsListCommand,"skillsListCommand");__name(normalizeRef,"normalizeRef");__name(skillsGetCommand,"skillsGetCommand")}});import{execFile as execFile8,spawnSync as spawnSync2}from"node:child_process";import path32 from"node:path";import{promisify as promisify8}from"node:util";function explainCreateProjectError(error){return error instanceof ApiRequestError&&error.detail.includes('insert into "projects"')&&(error.detail.includes('"subdomain"')||error.detail.includes('"subdomain_updated_at"'))?["Project creation failed because the local API database schema looks out of date.","The server is trying to write the `projects.subdomain` fields, but your database likely has not applied the latest migration yet.","Run `cd apps/api && pnpm db:migrate`, restart the API if needed, then retry."].join(`
596
- `):error instanceof Error?error.message:String(error)}async function scaffoldNewProject(args){let{api,cfg,targetDir,displayName,options}=args,organizationId=await resolveOrganization(api,options.org),createSpinner=spinner("Creating Fimo project"),project;try{project=await api.createProject({organizationId,displayName:displayName??path32.basename(targetDir)})}catch(error){throw createSpinner.fail("Project creation failed"),new ScaffoldError("PROJECT_CREATE_FAILED",explainCreateProjectError(error))}createSpinner.succeed(`Project ${project.displayName??project.name} created (${project.id})`);let releaseAbort=installAbortHandler(api,project.id,project.name);try{return{scaffold:await scaffoldIntoProject({project,api,cfg,targetDir,options}),releaseAbort}}catch(error){throw releaseAbort(),error}}async function scaffoldIntoProject(args){let{project,api,cfg,targetDir,options}=args,remoteSp=spinner("Fetching git remote"),remote=await api.getGitRemote(project.id,MAIN_BRANCH);remoteSp.succeed("Remote ready");let selectedAgents;try{selectedAgents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills})}catch(err){throw new ScaffoldError("AGENT_SELECTION_FAILED",err instanceof Error?err.message:String(err))}let scaffoldSp=spinner("Scaffolding template"),templateRoot=options.templateRoot?path32.resolve(options.templateRoot):process.env.FIMO_TEMPLATE_ROOT?path32.resolve(process.env.FIMO_TEMPLATE_ROOT):resolveTemplateRoot();await copyTemplate(templateRoot,targetDir),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiUrl:remote.tenantApiUrl});let gitSp=spinner("Initializing git repository");await runGit(["init","-b",MAIN_BRANCH],targetDir),await ensureFimoRemote(targetDir,remote.url),gitSp.succeed("Git initialized with `fimo` remote"),scaffoldSp.succeed("Template scaffolded");let relativeTarget=path32.relative(process.cwd(),targetDir)||".";return{project,targetDir,relativeTarget,selectedAgents,tenantApiUrl:remote.tenantApiUrl}}async function finalizeInitialCommit(args){let{targetDir}=args,gitSp=spinner("Creating the initial commit");await runGit(["add","-A"],targetDir),await runGit(["commit","-m","chore: scaffold Fimo project"],targetDir).catch(()=>{}),gitSp.succeed("Initial commit created");let pushSp=spinner("Pushing initial commit to Fimo");try{return await runGit(["push","fimo",`HEAD:${MAIN_BRANCH}`],targetDir),pushSp.succeed("Initial commit pushed"),{pushedInitial:!0}}catch(error){pushSp.fail("Initial push failed");let failure=classifyPushError(error),retryHint=failure.kind==="auth"?"Sign in with `fimo login`, then run `fimo deploy` to push it.":"Run `fimo deploy` later to retry.";return O2.error(`Could not push the initial commit. ${retryHint}
596
+ `):error instanceof Error?error.message:String(error)}async function scaffoldNewProject(args){let{api,cfg,targetDir,displayName,options}=args,organizationId=await resolveOrganization(api,options.org),createSpinner=spinner("Creating Fimo project"),project;try{project=await api.createProject({organizationId,displayName:displayName??path32.basename(targetDir)})}catch(error){throw createSpinner.fail("Project creation failed"),new ScaffoldError("PROJECT_CREATE_FAILED",explainCreateProjectError(error))}createSpinner.succeed(`Project ${project.displayName??project.name} created (${project.id})`);let releaseAbort=installAbortHandler(api,project.id,project.name);try{return{scaffold:await scaffoldIntoProject({project,api,cfg,targetDir,options}),releaseAbort}}catch(error){throw releaseAbort(),error}}async function scaffoldIntoProject(args){let{project,api,cfg,targetDir,options}=args,remoteSp=spinner("Fetching git remote"),remote=await api.getGitRemote(project.id,MAIN_BRANCH);remoteSp.succeed("Remote ready");let selectedAgents;try{selectedAgents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills})}catch(err){throw new ScaffoldError("AGENT_SELECTION_FAILED",err instanceof Error?err.message:String(err))}let scaffoldSp=spinner("Scaffolding template"),templateRoot=options.templateRoot?path32.resolve(options.templateRoot):process.env.FIMO_TEMPLATE_ROOT?path32.resolve(process.env.FIMO_TEMPLATE_ROOT):resolveTemplateRoot();await copyTemplate(templateRoot,targetDir),seedSiteName({targetDir,project}),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiUrl:remote.tenantApiUrl});let gitSp=spinner("Initializing git repository");await runGit(["init","-b",MAIN_BRANCH],targetDir),await ensureFimoRemote(targetDir,remote.url),gitSp.succeed("Git initialized with `fimo` remote"),scaffoldSp.succeed("Template scaffolded");let relativeTarget=path32.relative(process.cwd(),targetDir)||".";return{project,targetDir,relativeTarget,selectedAgents,tenantApiUrl:remote.tenantApiUrl}}async function finalizeInitialCommit(args){let{targetDir}=args,gitSp=spinner("Creating the initial commit");await runGit(["add","-A"],targetDir),await runGit(["commit","-m","chore: scaffold Fimo project"],targetDir).catch(()=>{}),gitSp.succeed("Initial commit created");let pushSp=spinner("Pushing initial commit to Fimo");try{return await runGit(["push","fimo",`HEAD:${MAIN_BRANCH}`],targetDir),pushSp.succeed("Initial commit pushed"),{pushedInitial:!0}}catch(error){pushSp.fail("Initial push failed");let failure=classifyPushError(error),retryHint=failure.kind==="auth"?"Sign in with `fimo login`, then run `fimo deploy` to push it.":"Run `fimo deploy` later to retry.";return O2.error(`Could not push the initial commit. ${retryHint}
597
597
  ${failure.stderr||""}`.trim()),{pushedInitial:!1}}}function installAbortHandler(api,projectId,projectName){let cleaningUp=!1,handler=__name(()=>{cleaningUp&&(process.stderr.write(`
598
598
  Force-exiting. Project may not have been fully cleaned up.
599
599
  `),process.exit(130)),cleaningUp=!0,process.stderr.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fimo",
3
- "version": "0.10.0-staging.1",
3
+ "version": "0.10.0-staging.2",
4
4
  "description": "Fimo CLI - create, deploy, and manage Fimo projects",
5
5
  "bin": {
6
6
  "fimo": "dist/cli/index.js"
@@ -21,7 +21,7 @@
21
21
  "cmdk": "^1.1.1",
22
22
  "date-fns": "^4.1.0",
23
23
  "embla-carousel-react": "^8.6.0",
24
- "fimo": "0.10.0-staging.1",
24
+ "fimo": "0.10.0-staging.2",
25
25
  "input-otp": "^1.4.2",
26
26
  "isbot": "^5",
27
27
  "lucide-react": "^0.577.0",