fimo 0.7.0-staging.4 → 0.7.1-staging.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "bundled": true,
3
3
  "bundler": "esbuild",
4
- "bundledAt": "2026-07-21T10:17:42.754Z",
5
- "cliVersion": "0.6.0",
4
+ "bundledAt": "2026-07-21T14:09:18.384Z",
5
+ "cliVersion": "0.7.0",
6
6
  "external": [
7
7
  "oxc-parser",
8
8
  "fsevents",
package/dist/cli/index.js CHANGED
@@ -435,7 +435,7 @@ ${end2.comment}`:end2.comment}this.doc.range[2]=end2.offset;break}default:this.e
435
435
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
436
436
  `,nl)+1}return{type,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(parent2){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return start.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let prev2=getPrevProps(parent2),start=getFirstKeyStartProps(prev2);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(start,indent){return this.type!=="comment"||this.indent<=indent?!1:start.every(st2=>st2.type==="newline"||st2.type==="space")}*documentEnd(docEnd){this.type!=="doc-mode"&&(docEnd.end?docEnd.end.push(this.sourceToken):docEnd.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(token){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:token.end?token.end.push(this.sourceToken):token.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};exports2.Parser=Parser2}});var require_public_api2=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/public-api.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),errors=require_errors2(),log=require_log2(),identity2=require_identity2(),lineCounter=require_line_counter2(),parser=require_parser3();function parseOptions(options){let prettyErrors=options.prettyErrors!==!1;return{lineCounter:options.lineCounter||prettyErrors&&new lineCounter.LineCounter||null,prettyErrors}}__name(parseOptions,"parseOptions");function parseAllDocuments(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),docs=Array.from(composer$1.compose(parser$1.parse(source)));if(prettyErrors&&lineCounter2)for(let doc of docs)doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2));return docs.length>0?docs:Object.assign([],{empty:!0},composer$1.streamInfo())}__name(parseAllDocuments,"parseAllDocuments");function parseDocument2(source,options={}){let{lineCounter:lineCounter2,prettyErrors}=parseOptions(options),parser$1=new parser.Parser(lineCounter2?.addNewLine),composer$1=new composer.Composer(options),doc=null;for(let _doc of composer$1.compose(parser$1.parse(source),!0,source.length))if(!doc)doc=_doc;else if(doc.options.logLevel!=="silent"){doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return prettyErrors&&lineCounter2&&(doc.errors.forEach(errors.prettifyError(source,lineCounter2)),doc.warnings.forEach(errors.prettifyError(source,lineCounter2))),doc}__name(parseDocument2,"parseDocument");function parse12(src,reviver,options){let _reviver;typeof reviver=="function"?_reviver=reviver:options===void 0&&reviver&&typeof reviver=="object"&&(options=reviver);let doc=parseDocument2(src,options);if(!doc)return null;if(doc.warnings.forEach(warning=>log.warn(doc.options.logLevel,warning)),doc.errors.length>0){if(doc.options.logLevel!=="silent")throw doc.errors[0];doc.errors=[]}return doc.toJS(Object.assign({reviver:_reviver},options))}__name(parse12,"parse");function stringify4(value,replacer,options){let _replacer=null;if(typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer),typeof options=="string"&&(options=options.length),typeof options=="number"){let indent=Math.round(options);options=indent<1?void 0:indent>8?{indent:8}:{indent}}if(value===void 0){let{keepUndefined}=options??replacer??{};if(!keepUndefined)return}return identity2.isDocument(value)&&!_replacer?value.toString(options):new Document2.Document(value,_replacer,options).toString(options)}__name(stringify4,"stringify");exports2.parse=parse12;exports2.parseAllDocuments=parseAllDocuments;exports2.parseDocument=parseDocument2;exports2.stringify=stringify4}});var require_dist2=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/index.js"(exports2){"use strict";var composer=require_composer2(),Document2=require_Document2(),Schema=require_Schema2(),errors=require_errors2(),Alias=require_Alias2(),identity2=require_identity2(),Pair=require_Pair2(),Scalar=require_Scalar2(),YAMLMap=require_YAMLMap2(),YAMLSeq=require_YAMLSeq2(),cst=require_cst2(),lexer=require_lexer2(),lineCounter=require_line_counter2(),parser=require_parser3(),publicApi=require_public_api2(),visit2=require_visit2();exports2.Composer=composer.Composer;exports2.Document=Document2.Document;exports2.Schema=Schema.Schema;exports2.YAMLError=errors.YAMLError;exports2.YAMLParseError=errors.YAMLParseError;exports2.YAMLWarning=errors.YAMLWarning;exports2.Alias=Alias.Alias;exports2.isAlias=identity2.isAlias;exports2.isCollection=identity2.isCollection;exports2.isDocument=identity2.isDocument;exports2.isMap=identity2.isMap;exports2.isNode=identity2.isNode;exports2.isPair=identity2.isPair;exports2.isScalar=identity2.isScalar;exports2.isSeq=identity2.isSeq;exports2.Pair=Pair.Pair;exports2.Scalar=Scalar.Scalar;exports2.YAMLMap=YAMLMap.YAMLMap;exports2.YAMLSeq=YAMLSeq.YAMLSeq;exports2.CST=cst;exports2.Lexer=lexer.Lexer;exports2.LineCounter=lineCounter.LineCounter;exports2.Parser=parser.Parser;exports2.parse=publicApi.parse;exports2.parseAllDocuments=publicApi.parseAllDocuments;exports2.parseDocument=publicApi.parseDocument;exports2.stringify=publicApi.stringify;exports2.visit=visit2.visit;exports2.visitAsync=visit2.visitAsync}});import fs10 from"node:fs";import path11 from"node:path";function loadProjectSettings(cwd){let settingsPath=path11.join(cwd,".fimo.settings.json");if(!fs10.existsSync(settingsPath))throw new Error("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project.");return JSON.parse(fs10.readFileSync(settingsPath,"utf-8"))}function findProjectRoot(start){let dir=path11.resolve(start);for(;;){if(fs10.existsSync(path11.join(dir,".fimo.settings.json")))return dir;let parent2=path11.dirname(dir);if(parent2===dir)return null;dir=parent2}}function resolveProjectCwd(cwdOption){let start=path11.resolve(cwdOption??process.cwd());return findProjectRoot(start)??start}var init_project=__esm({"src/cli/utils/project.ts"(){__name(loadProjectSettings,"loadProjectSettings");__name(findProjectRoot,"findProjectRoot");__name(resolveProjectCwd,"resolveProjectCwd")}});function colorEnabled(opts={}){if(opts.forceDisable)return!1;let env=opts.env??process.env;return env.NO_COLOR&&env.NO_COLOR.length>0?!1:env.FORCE_COLOR&&env.FORCE_COLOR!=="0"&&env.FORCE_COLOR!=="false"?!0:(opts.isTTY??process.stdout.isTTY??!1)===!0}function makeColorPalette(opts={}){let on=colorEnabled(opts),wrap2=__name(style=>s=>on?`${ANSI[style]}${s}${ANSI.reset}`:s,"wrap");return{enabled:on,bold:wrap2("bold"),dim:wrap2("dim"),red:wrap2("red"),green:wrap2("green"),yellow:wrap2("yellow"),blue:wrap2("blue"),magenta:wrap2("magenta"),cyan:wrap2("cyan"),gray:wrap2("gray")}}var ANSI,palette,init_color=__esm({"src/cli/utils/format/color.ts"(){ANSI={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};__name(colorEnabled,"colorEnabled");__name(makeColorPalette,"makeColorPalette");palette=makeColorPalette()}});function isCliAuthError(err){return err instanceof NotAuthenticatedError||err instanceof UnauthorizedError||err instanceof PermissionDeniedError}function rethrowCliAuthError(err,beforeThrow){if(isCliAuthError(err))throw beforeThrow?.(err),err}function retryCommand(args=process.argv.slice(2)){return["fimo",...args].map(formatShellArg).join(" ")}function formatCliAuthError(err,opts={}){let p2=opts.palette??palette,command=retryCommand(opts.args);if(err instanceof PermissionDeniedError)return[`${p2.red("\u2717")} You don't have permission to run this command.`,"",err.required.length?` Missing permission: ${p2.bold(err.required.join(", "))}`:" Your role on this project does not allow this action."," Ask a project admin for access, or use an account with a higher role.","",p2.dim(` Backend: ${err.apiUrl}`)].join(`
437
437
  `);let expired=err instanceof UnauthorizedError,intro=expired?"Your Fimo session is expired or invalid.":"You're not signed in to Fimo.",loginVerb=expired?"refresh your session":"sign in";return[`${p2.red("\u2717")} ${intro}`,"",` Run this to ${loginVerb}:`,` ${p2.bold("fimo login")}`,""," Then retry:",` ${p2.bold(command)}`,"",p2.dim(` Backend: ${err.apiUrl}`)].join(`
438
- `)}function renderCliAuthError(err,opts={}){console.error(formatCliAuthError(err,opts))}function formatShellArg(arg){return/^[A-Za-z0-9_/:=.,@%+-]+$/.test(arg)?arg:`'${arg.replace(/'/g,"'\\''")}'`}var init_auth_errors=__esm({"src/cli/utils/auth-errors.ts"(){init_api();init_auth();init_color();__name(isCliAuthError,"isCliAuthError");__name(rethrowCliAuthError,"rethrowCliAuthError");__name(retryCommand,"retryCommand");__name(formatCliAuthError,"formatCliAuthError");__name(renderCliAuthError,"renderCliAuthError");__name(formatShellArg,"formatShellArg")}});import{z as z7}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z7.ZodOptional||schema instanceof z7.ZodNullable||schema instanceof z7.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z7.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z7.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z7.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z7.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z7.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z7.ZodObject)return createObjectDTO(schema);if(schema instanceof z7.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z8}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z8.object({data:dataSchema}),"createResponseSchema")}});import{z as z9}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z9.object({page:z9.coerce.number().int().positive().default(1),limit:z9.coerce.number().int().positive().max(100).default(20)})}});import{z as z10}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z10.coerce.date(),positiveInt:z10.number().int().positive(),nonNegativeInt:z10.number().int().nonnegative()},BaseEntitySchema=z10.object({id:z10.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z10.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z10.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z10.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z10.enum(["public","private"]),ProjectStatusSchema=z10.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z10.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z10.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z10.enum(["owner","admin","member"]),AssetTypeSchema=z10.enum(["file","folder"]),TemplateCodeSchema=z10.enum(["Free","Premium"]),FieldTypeSchema=z10.enum(["string","richtext","media","number","boolean","date","json","reference"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as z11}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z11.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z12}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var ReferenceValueSchema,PolymorphicReferenceValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");ReferenceValueSchema=z12.preprocess(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({documentId:z12.uuid()}));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");PolymorphicReferenceValueSchema=z12.preprocess(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({contentType:z12.string().min(1),documentId:z12.uuid()}))}});import{z as z13}from"zod";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_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=z13.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z13.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z13.enum(AUDIT_ACTOR_KINDS)}});import{z as z14}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=z14.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=z14.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=z14.object({permissions:z14.array(OpsPermissionSchema).min(1),backendProfiles:z14.array(OpsBackendProfileSchema).min(1),enabled:z14.boolean().default(!0)}),OpsServiceTokenInputSchema=z14.object({name:z14.string().trim().min(1).max(120),permissions:z14.array(OpsPermissionSchema).min(1),backendProfiles:z14.array(OpsBackendProfileSchema).min(1),expiresAt:z14.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=z14.object({importanceReason:z14.string().trim().min(1).max(1e3),ownerUserId:z14.string().trim().min(1).nullable().optional(),framework:z14.string().trim().max(120).nullable().optional(),packageManager:z14.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z14.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z14.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z14.object({projectId:z14.uuid(),title:z14.string().trim().min(1).max(240),userReport:z14.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z14.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z14.string().trim().max(1e4).nullable().optional(),outcome:z14.string().trim().max(1e4).nullable().optional(),evidence:z14.array(z14.record(z14.string(),z14.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=z14.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z14.object({fingerprint:z14.string().trim().min(1).max(240),title:z14.string().trim().min(1).max(240),description:z14.string().trim().min(1).max(1e4),affectedVersions:z14.array(z14.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z14.array(z14.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z14.string().trim().min(1).max(64).nullable().optional(),workaround:z14.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z14.array(z14.string().trim().min(1).max(120)).max(100),detectionQueries:z14.array(z14.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=z14.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z14.object({changeReference:z14.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z14.string().trim().min(1).max(1e4),evidence:z14.array(z14.record(z14.string(),z14.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z14.object({recipientEmail:z14.email().optional(),subject:z14.string().trim().min(1).max(200).default("An update from Fimo"),message:z14.string().trim().min(1).max(5e3),locale:z14.string().trim().min(2).max(20),reason:z14.string().trim().min(1).max(1e3),acknowledgePolicy:z14.literal(!0)})}});import{z as z15}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:z15.string(),displayName:z15.string().nullable(),subdomain:z15.string().nullable().optional(),subdomainUpdatedAt:z15.date().nullable().optional(),organizationId:z15.string().nullable(),createdBy:z15.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z15.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z15.string(),thumbnailUrl:z15.string().nullable(),publishedThumbnailUrl:z15.string().nullable(),category:z15.string().nullable(),appUrl:z15.string().nullable(),lastPublishedAt:z15.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z15.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z15.object({id:z15.uuid(),name:z15.string(),displayName:z15.string().nullable(),thumbnailUrl:z15.string().nullable(),visibility:ProjectVisibilitySchema,category:z15.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z15.object({id:z15.string(),name:z15.string(),avatar:z15.string().nullable(),color:z15.object({bg:z15.string(),text:z15.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z15.object({path:z15.string(),content:z15.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z15.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z15.object({id:z15.string(),messageId:z15.string(),versionId:z15.string().nullable(),role:ProjectChatMessageRole,parts:z15.array(z15.any()),createdAt:z15.coerce.date()}),MessageUserMetadataSchema=z15.object({id:z15.string(),name:z15.string().nullable().optional(),image:z15.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z15.object({shortTitle:z15.string().optional(),questions:z15.array(z15.object({header:z15.string(),question:z15.string(),answer:z15.string(),selectedLabels:z15.array(z15.string()),freeText:z15.string(),skipped:z15.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z15.number(),metadata:z15.object({user:MessageUserMetadataSchema,changeManifest:z15.array(z15.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z15.object({id:z15.uuid(),versionId:z15.string(),projectId:z15.uuid(),commitHash:z15.string(),name:z15.string(),description:z15.string().nullable(),thumbnailUrl:z15.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z15.object({content:z15.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z15.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z15.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z15.object({success:z15.boolean(),message:z15.string().optional()})),ProjectPublicationStateDTOSchema=z15.object({isPublished:z15.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z15.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z15.object({success:z15.boolean(),message:z15.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z16}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=z16.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z16.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z16.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z16.string().nullable(),deletedAt:z16.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z16.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z16.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z16.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z16.object({surface:z16.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z16.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z16.number().int().nonnegative(),conflictCount:z16.number().int().nonnegative()}),EnvDiffResultSchema=z16.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z16.coerce.date(),surfaces:z16.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z17}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=z17.object({success:z17.literal(!0),downloadUrl:z17.string(),expiresAt:z17.string(),fileSize:z17.number(),duration:z17.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z17.object({success:z17.literal(!0),projectId:z17.string(),projectName:z17.string(),displayName:z17.string(),projectUrl:z17.string(),duration:z17.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z17.object({contentTypes:z17.number(),entries:z17.number(),assets:z17.number(),translations:z17.number(),forms:z17.number(),codeFiles:z17.number(),assetFiles:z17.number()}),ImportPreviewSurfaceDTOSchema=z17.object({name:z17.string(),included:z17.boolean(),count:z17.number().optional(),note:z17.string().optional()}),ImportPreviewDTOSchema=z17.object({projectName:z17.string(),displayName:z17.string().nullable(),visibility:z17.string().nullable(),category:z17.string().nullable(),exportedAt:z17.string(),version:z17.string(),envScope:z17.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z17.array(ImportPreviewSurfaceDTOSchema),fileSize:z17.number(),fileName:z17.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z17.object({success:z17.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z18}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=z18.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z18.object({type:z18.literal("manual")}),ScheduleTriggerSchema=z18.object({type:z18.literal("schedule"),cron:z18.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:z18.string().optional()}),WebhookTriggerSchema2=z18.object({type:z18.literal("webhook"),path:z18.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z18.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z19}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=z19.object({triggerIndices:z19.array(z19.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z19.object({triggerIndices:z19.array(z19.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z19.object({projectId:z19.uuid(),env:EnvSchema,agentName:z19.string().min(1),triggerIndex:z19.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z19.boolean(),lastFiredAt:z19.coerce.date().nullable(),webhookPath:z19.string().nullable(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z19.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z19.object({error:z19.literal("webhook_path_taken"),conflictAgent:z19.string(),path:z19.string()}),ManualRunRequestSchema=z19.object({args:z19.unknown().optional(),requestId:z19.string().min(1).max(128).optional()}),DispatchSkippedSchema=z19.object({skipped:z19.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z19.object({sessionId:z19.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z19.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z20}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=z20.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z20.object({token:z20.string().min(1),risk:CapabilityRiskTierSchema,description:z20.string()}),AgentSubAgentSummarySchema=z20.object({name:z20.string().min(1),grant:z20.enum(["inherit","explicit"]),effectiveCaps:z20.array(z20.string().min(1))}),AgentInstallSummaryDTOSchema=z20.object({agentName:z20.string().min(1),env:z20.string().min(1),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z20.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z20.array(CapabilitySummaryEntrySchema),criticalCapabilities:z20.array(CapabilitySummaryEntrySchema),subAgents:z20.array(AgentSubAgentSummarySchema),declaresDelegate:z20.boolean(),cycle:z20.array(z20.string()).nullable(),missingSubAgents:z20.array(z20.string()),warnings:z20.array(z20.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z21}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=z21.object({kind:TriggerKindSchema,summary:z21.string()}),AgentListItemActivationSchema=z21.object({triggerIndex:z21.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z21.string().min(1),active:z21.boolean()}),AgentListItemDTOSchema=z21.object({name:z21.string().min(1),description:z21.string().nullable(),goalFirstLine:z21.string().nullable(),declaredCapabilities:z21.array(CapabilitySummaryEntrySchema),triggers:z21.array(AgentListItemTriggerSchema),activations:z21.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z21.array(AgentListItemDTOSchema))}});import{z as z22}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=z22.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z22.object({cpuMs:z22.number().nonnegative().default(0),netBytes:z22.number().nonnegative().default(0),walltimeMs:z22.number().nonnegative().default(0),llmTokensIn:z22.number().nonnegative().optional(),llmTokensOut:z22.number().nonnegative().optional()}),AgentSessionDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),env:EnvSchema,agentName:z22.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z22.unknown().optional(),capabilities:z22.array(z22.string()).optional(),dataSources:z22.array(z22.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z22.string().nullable(),startedAt:z22.coerce.date().nullable(),finishedAt:z22.coerce.date().nullable(),cancelledAt:z22.coerce.date().nullable(),costUsd:z22.number().nonnegative(),costCeilingUsd:z22.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z22.boolean(),lastCheckpointId:z22.uuid().nullable(),branchEnvId:z22.uuid().nullable(),parentSessionId:z22.uuid().nullable(),terminalReason:z22.string().nullable(),errorMessage:z22.string().nullable(),report:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z22.object({id:z22.uuid(),sessionId:z22.uuid(),checkpointIdx:z22.number().int().nonnegative(),payloadRef:z22.string(),payloadSizeBytes:z22.number().int().nonnegative(),checksum:z22.string().length(64),createdAt:z22.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z22.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z22.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z22.object({session:AgentSessionDTOSchema,checkpoints:z22.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z22.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z22.object({reason:z22.string().min(1).max(120).optional()})}});import{z as z23}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=z23.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z23.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z23.object({id:z23.uuid(),envId:z23.uuid(),sessionId:z23.uuid().nullable(),skillName:z23.string().min(1),classification:AgentBranchClassificationSchema,rationale:z23.string().nullable(),summary:z23.string().nullable(),surfaceDeltas:z23.record(z23.string(),z23.unknown()),createdAt:z23.coerce.date(),decidedAt:z23.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z23.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z23.object({path:z23.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z23.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z23.object({code:z23.literal("merge_conflict"),message:z23.string(),conflicts:z23.record(z23.string(),z23.number().int().nonnegative())})}});import{z as z24}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=z24.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z24.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z24.enum(["secret_text"]),IntegrationCredentialUsageSchema=z24.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z24.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z24.object({mode:IntegrationAuthModeSchema,label:z24.string().min(1),description:z24.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z24.object({id:z24.string().min(1),label:z24.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z24.boolean()}),IntegrationToolDefinitionDTOSchema=z24.object({key:z24.string().min(1),name:z24.string().min(1),description:z24.string().min(1)}),IntegrationRecipeDTOSchema=z24.object({title:z24.string().min(1),description:z24.string().min(1),command:z24.string().min(1).optional()}),IntegrationInfoDTOSchema=z24.object({key:z24.string().min(1),name:z24.string().min(1),summary:z24.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z24.array(IntegrationAuthModeDTOSchema),credentials:z24.array(IntegrationCredentialDefinitionDTOSchema),tools:z24.array(IntegrationToolDefinitionDTOSchema),recipes:z24.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z24.object({projectId:z24.uuid(),integrationKey:z24.string().min(1),installed:z24.boolean(),enabled:z24.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z24.string().nullable(),connectionId:z24.uuid().nullable().optional(),connectionAlias:z24.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z24.array(z24.string()),installedAt:z24.coerce.date().nullable(),updatedAt:z24.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),integrationKey:z24.string().min(1),enabled:z24.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z24.string(),connectionId:z24.uuid().nullable().optional(),connectionAlias:z24.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z24.array(z24.string()),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z24.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z24.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z24.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z24.object({value:z24.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z24.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z24.object({id:z24.uuid(),organizationId:z24.string().min(1),integrationKey:z24.string().min(1),alias:z24.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z24.string().min(1),externalAccountName:z24.string().nullable(),externalBotUserId:z24.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z24.array(z24.string()),connectedAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z24.object({alias:z24.string().min(1).max(120).optional(),token:z24.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z24.object({integrationKey:z24.string().min(1),connectUrl:z24.string().url(),expiresAt:z24.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z24.object({ref:z24.string().min(1),connectionAlias:z24.string().min(1).optional(),agentName:z24.string().min(1).max(160).nullable().optional(),force:z24.boolean().optional()}),ProjectChannelBindingDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),integrationKey:z24.string().min(1),connectionId:z24.uuid(),externalWorkspaceId:z24.string().min(1),externalChannelId:z24.string().min(1),externalChannelName:z24.string().nullable(),agentName:z24.string().nullable(),enabled:z24.boolean(),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z24.object({markdown:z24.boolean().optional(),summary:z24.boolean().optional(),links:z24.boolean().optional(),images:z24.boolean().optional(),html:z24.union([z24.literal("cleaned"),z24.literal("raw"),z24.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z24.object({url:z24.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional(),waitForMs:z24.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z24.object({query:z24.string().min(1),maxResults:z24.number().int().positive().max(20).optional(),timeoutMs:z24.number().int().positive().max(12e4).optional()}),FirecrawlMapToolInputSchema=z24.object({url:z24.string().url(),search:z24.string().min(1).optional(),limit:z24.number().int().positive().max(200).optional(),includeSubdomains:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z24.object({url:z24.string().url(),limit:z24.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z24.object({text:z24.string().min(1).max(200).optional(),cron:z24.string().min(1).max(120).optional(),timezone:z24.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z24.object({type:z24.enum(["scrape","crawl"]).default("scrape"),urls:z24.array(z24.string().url()).min(1).max(50),scrapeOptions:z24.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional(),waitForMs:z24.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z24.object({name:z24.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z24.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z24.string().min(1).max(2e3).optional(),judgeEnabled:z24.boolean().optional(),retentionDays:z24.number().int().min(1).max(365).optional(),notification:z24.object({email:z24.object({enabled:z24.boolean().default(!0),recipients:z24.array(z24.string().email()).min(1).max(20),includeDiffs:z24.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z24.object({monitorId:z24.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z24.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z24.object({connectionAlias:z24.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z24.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.list"),input:z24.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z24.object({provider:z24.string().min(1),providerCredits:z24.number().nonnegative().optional(),providerCostUsd:z24.number().nonnegative().optional(),requests:z24.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z24.object({credits:z24.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z24.object({url:z24.string(),provider:z24.literal("firecrawl"),title:z24.string().optional(),statusCode:z24.number().optional(),markdown:z24.string().optional(),summary:z24.string().optional(),links:z24.array(z24.string()).optional(),images:z24.array(z24.string()).optional(),html:z24.string().optional(),warning:z24.string().optional()}),FirecrawlSearchToolOutputSchema=z24.object({query:z24.string(),provider:z24.literal("firecrawl"),results:z24.array(z24.object({title:z24.string(),url:z24.string(),snippet:z24.string().optional(),content:z24.string().optional(),score:z24.number().optional(),publishedAt:z24.string().optional()}))}),FirecrawlMapToolOutputSchema=z24.object({url:z24.string(),provider:z24.literal("firecrawl"),count:z24.number(),links:z24.array(z24.object({url:z24.string(),title:z24.string().optional(),description:z24.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z24.object({url:z24.string(),provider:z24.literal("firecrawl"),total:z24.number(),pages:z24.array(z24.object({url:z24.string(),title:z24.string().optional(),statusCode:z24.number().optional(),markdown:z24.string().optional(),summary:z24.string().optional(),links:z24.array(z24.string()).optional(),images:z24.array(z24.string()).optional(),html:z24.string().optional(),warning:z24.string().optional()})),warning:z24.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z24.object({cron:z24.string().optional(),text:z24.string().optional(),timezone:z24.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z24.object({id:z24.string().optional(),urls:z24.array(z24.string()).optional(),scrapeOptions:z24.record(z24.string(),z24.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z24.object({id:z24.string(),name:z24.string(),status:z24.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z24.string().nullable().optional(),lastRunAt:z24.string().nullable().optional(),currentCheckId:z24.string().nullable().optional(),targets:z24.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z24.string().nullable().optional(),judgeEnabled:z24.boolean().optional(),estimatedCreditsPerMonth:z24.number().optional(),createdAt:z24.string().optional(),updatedAt:z24.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z24.object({id:z24.string(),monitorId:z24.string(),scheduledFor:z24.string().nullable().optional(),startedAt:z24.string().nullable().optional(),finishedAt:z24.string().nullable().optional(),estimatedCredits:z24.number().optional(),reservedCredits:z24.number().optional(),actualCredits:z24.number().optional(),billingStatus:z24.string().nullable().optional(),summary:z24.object({totalPages:z24.number().optional(),same:z24.number().optional(),changed:z24.number().optional(),new:z24.number().optional(),removed:z24.number().optional(),error:z24.number().optional()}).passthrough().optional(),error:z24.string().nullable().optional(),createdAt:z24.string().optional(),updatedAt:z24.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitors:z24.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitorId:z24.string(),deleted:z24.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitorId:z24.string(),checks:z24.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitorId:z24.string(),check:FirecrawlMonitorCheckOutputSchema,next:z24.string().optional()}),FirecrawlToolKeySchema=z24.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z24.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z24.object({projectId:z24.uuid(),integrationKey:z24.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z24.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z24.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z24.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z24.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z24.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z24.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z24.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z24.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z24.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z24.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 z25}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=z25.enum(["ok","failed"]),ProjectScheduleDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),env:z25.string().min(1),name:z25.string().min(1),cron:z25.string().min(1),command:z25.string().min(1),enabled:z25.boolean(),lastRunAt:z25.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z25.string().nullable(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z25.object({name:z25.string().min(1).max(120),cron:z25.string().min(1).max(120),command:z25.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z25.array(ProjectScheduleDTOSchema))}});import{z as z26}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=z26.object({id:z26.uuid(),occurredAt:z26.coerce.date(),projectId:z26.uuid().nullable(),env:z26.string().nullable(),actor:z26.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z26.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z26.unknown().optional(),ipAddress:z26.string().nullable().optional(),userAgent:z26.string().nullable().optional(),error:z26.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z26.object({rows:z26.array(AuditLogRowDTOSchema),nextCursor:z26.string().nullable()})),AuditLogQuerySchema=z26.object({env:z26.string().optional(),action:AuditActionSchema.optional(),actor:z26.string().optional(),from:z26.coerce.date().optional(),to:z26.coerce.date().optional(),limit:z26.coerce.number().int().min(1).max(200).optional(),cursor:z26.string().optional()})}});import{z as z27}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,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=z27.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z27.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z27.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z27.object({verb:SurfaceDeltaVerbSchema,key:z27.string(),detail:z27.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z27.record(z27.string(),z27.unknown()).optional()}),PerSurfaceDeltaSchema=z27.object({surface:SurfaceNameSchema,status:z27.enum(["ok","timed_out","failed","unchanged"]),durationMs:z27.number().int().nonnegative().optional(),changedCount:z27.number().int().nonnegative(),conflictCount:z27.number().int().nonnegative(),items:z27.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z27.boolean().optional(),error:z27.string().optional()}),CrossSurfaceFindingSchema=z27.object({id:z27.string(),kind:z27.string(),description:z27.string(),severity:z27.enum(["warning","error"]),source:z27.object({surface:SurfaceNameSchema,key:z27.string()}),target:z27.object({surface:SurfaceNameSchema,key:z27.string()}),actions:z27.array(z27.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z27.object({env:EnvSchema,vs:EnvSchema,syncState:z27.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),agents:z27.array(z27.object({id:z27.string(),name:z27.string(),status:z27.enum(["active","paused","failed"]),lastRunAt:z27.coerce.date().nullable()})).optional(),crossSurface:z27.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z27.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),crossSurface:z27.array(CrossSurfaceFindingSchema).optional(),fingerprint:z27.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z27.object({path:z27.string(),state:z27.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z27.string(),additions:z27.number().int().nonnegative(),deletions:z27.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z27.object({oid:z27.string().optional(),content:z27.string().optional(),truncated:z27.boolean(),binary:z27.boolean()}),CodeConflictDetailSchema=z27.object({path:z27.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z27.string(),targetTipSha:z27.string(),mergeBaseSha:z27.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z27.object({id:z27.string(),slug:z27.string(),contentType:z27.string(),data:z27.record(z27.string(),z27.unknown()),updatedAt:z27.coerce.date()}),ContentRowDiffSchema=z27.object({collection:z27.string(),rowId:z27.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z27.object({name:z27.string(),label:z27.string(),isSingleton:z27.boolean(),fields:z27.record(z27.string(),z27.unknown())}),SchemaTypeDiffSchema=z27.object({typeName:z27.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z27.object({id:z27.string(),name:z27.string(),type:z27.enum(["file","folder"]),mimeType:z27.string().nullable(),storageKey:z27.string().nullable(),url:z27.string().nullable(),fileSize:z27.number().nullable(),width:z27.number().nullable(),height:z27.number().nullable(),altText:z27.string().nullable(),caption:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AssetDiffSchema=z27.object({assetId:z27.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z27.object({locale:z27.string(),key:z27.string(),parent:z27.string().nullable(),child:z27.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z27.object({formName:z27.string(),label:z27.string().nullable(),schemaFingerprint:z27.string(),fields:z27.record(z27.string(),z27.unknown()),settings:z27.record(z27.string(),z27.unknown()).optional()}),FormSchemaDiffSchema=z27.object({formName:z27.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z27.object({agentName:z27.string(),triggerIndex:z27.number().int().nonnegative(),triggerKind:z27.string(),triggerSpec:z27.record(z27.string(),z27.unknown()),enabled:z27.boolean(),emailRecipients:z27.array(z27.string()).nullable(),qstashScheduleId:z27.string().nullable()}),ActivationDiffSchema=z27.object({agentName:z27.string(),triggerIndex:z27.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),ConflictSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),kind:z27.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity"]).optional(),description:z27.string(),parentValue:z27.unknown().optional(),childValue:z27.unknown().optional(),conflictingFields:z27.array(z27.string()).optional(),code:z27.object({path:z27.string(),unresolvable:z27.boolean().optional(),reason:z27.string().optional()}).optional()}),FieldPickSchema=z27.object({field:z27.string(),choice:z27.enum(["parent","child","pick","ai-pick"]),pickedValue:z27.unknown().optional(),aiSessionId:z27.string().optional()}),ConflictResolutionSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),choice:z27.enum(["parent","child","pick"]),pickedValue:z27.unknown().optional(),fieldPicks:z27.array(FieldPickSchema).optional()}),MergeResultSchema=z27.object({ok:z27.boolean(),mergeId:z27.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z27.array(z27.object({surface:SurfaceNameSchema,count:z27.number().int().nonnegative()})),conflicts:z27.array(ConflictSchema).optional(),summary:z27.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z27.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z27.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z27.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z27.boolean().optional()}),ResolvedStrategySchema=z27.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z27.boolean()}),MergeRequestSchema=z27.object({from:EnvSchema,allowDirectMerge:z27.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z27.object({mergeId:z27.string().uuid(),streamUrl:z27.string(),strategy:ResolvedStrategySchema,acceptedAt:z27.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z27.object({mergeId:z27.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z27.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z27.array(ConflictSchema),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedBy:z27.string().nullable(),lastEditedAt:z27.coerce.date().nullable(),initiator:z27.object({userId:z27.string().nullable(),role:z27.string().nullable(),agentName:z27.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z27.object({resolutions:z27.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z27.object({mergeId:z27.string().uuid(),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedAt:z27.coerce.date(),lastEditedBy:z27.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z27.object({mergeId:z27.string().uuid(),resolutions:z27.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z27.object({mergeId:z27.string().uuid()}),PublishReleaseRequestSchema=z27.object({version:z27.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z27.string().max(2e4).optional()}),PublishReleaseResultSchema=z27.object({releaseTag:z27.string(),sha:z27.string(),publishedAt:z27.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z28}from"zod";var 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=z28.object({surface:SurfaceNameSchema,key:z28.string(),label:z28.string()}),InlineSchema=z28.object({text:z28.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z28.discriminatedUnion("type",[z28.object({type:z28.literal("paragraph"),content:z28.array(InlineSchema).max(24)}),z28.object({type:z28.literal("preview"),ref:DiffRefSchema,caption:z28.string().optional()}),z28.object({type:z28.literal("code"),code:z28.string(),lang:z28.string().optional(),caption:z28.string().optional()}),z28.object({type:z28.literal("risk"),level:z28.enum(["warning","error"]),content:z28.array(InlineSchema).max(24)}),z28.object({type:z28.literal("list"),items:z28.array(z28.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z28.object({headline:z28.string(),blocks:z28.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z28.object({summary:EnvDiffSummarySchema,fingerprint:z28.string(),generatedAt:z28.coerce.date(),cached:z28.boolean().optional(),credits:z28.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z29}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=z29.object({date:z29.string(),visitors:z29.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z29.object({key:z29.string(),visitors:z29.number().int().nonnegative(),pageviews:z29.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z29.object({path:z29.string(),pageName:z29.string().nullable().optional(),visitors:z29.number().int().nonnegative(),pageviews:z29.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z29.object({preset:z29.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z29.string(),requestedTo:z29.string(),effectiveFrom:z29.string(),effectiveTo:z29.string(),isRetentionLimited:z29.boolean(),groupBy:z29.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z29.object({date:z29.string(),content:z29.string(),updatedAt:z29.string(),updatedByUserId:z29.string()}),ProjectPageviewAnalyticsDTOSchema=z29.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z29.number().int().nonnegative(),pageviews:z29.number().int().nonnegative(),bounceRate:z29.number().min(0).max(100),viewsPerVisit:z29.number().nonnegative(),averageVisitDurationSeconds:z29.number().nonnegative(),visitorsSeries:z29.array(ProjectDailyVisitorsDTOSchema),topPages:z29.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z29.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z30}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=z30.object({id:z30.string(),email:z30.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z30.coerce.date(),createdAt:z30.coerce.date(),inviterUserId:z30.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z30.object({id:z30.string(),token:z30.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z30.object({success:z30.boolean(),projectId:z30.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z31}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=z31.object({id:z31.string(),name:z31.string(),image:z31.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z31.object({count:z31.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z31.object({counts:z31.object({signed_up:z31.int(),activated:z31.int()}),credits:z31.object({total:z31.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z31.email(),emailVerified:z31.boolean(),createdAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z32}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=z32.object({id:z32.string(),principalType:ProjectPrincipalTypeSchema,principalId:z32.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z32.coerce.date(),expiresAt:z32.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z32.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z32.record(z32.string(),z32.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z32.object({access:z32.array(ProjectAccessItemDTOSchema),invites:z32.array(ProjectInviteDTOSchema),organization:z32.object({name:z32.string().nullable(),logo:z32.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z32.object({success:z32.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z32.object({success:z32.boolean(),projectId:z32.uuid()}))}});import{z as z33}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=z33.object({publicationStatus:PublicationStatusSchema,appUrl:z33.string().nullable(),lastPublishedAt:z33.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z34}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=z34.object({url:z34.url(),expiresAt:z34.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z34.discriminatedUnion("source",[z34.object({source:z34.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z34.null()}),z34.object({source:z34.literal("dev"),artifact:z34.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z35}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:z35.string(),slug:z35.string().nullable(),logo:z35.string().nullable(),metadata:z35.record(z35.string(),z35.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z35.object({id:z35.string(),name:z35.string(),email:z35.email(),image:z35.string().nullable()}),OrganizationMemberDTOSchema=z35.object({id:z35.string(),userId:z35.string(),organizationId:z35.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z35.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z36}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=z36.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z36.object({reason:CancellationReasonCodeSchema,details:z36.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z36.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z36.object({included:z36.number().optional(),unitPrice:z36.number().optional(),dailyCap:z36.number().nullable().optional()}),EntitlementsDTOSchema=z36.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z36.object({retentionDays:z36.number().int().positive(),canUseExtendedDateRanges:z36.boolean()}).optional(),members:z36.object({canInvite:z36.boolean(),maxMembers:z36.number().int().positive().nullable()}).optional(),projects:z36.object({canCreatePrivateProjects:z36.boolean(),maxPrivateProjects:z36.number().int().positive().nullable()}).optional(),domains:z36.object({canUseCustomDomains:z36.boolean(),maxDomains:z36.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z36.object({id:z36.string(),external_id:z36.string(),customerId:z36.string(),planId:z36.string(),planCode:TemplateCodeSchema,currentPeriod:z36.object({start:z36.string(),end:z36.string().nullable()}),cancelAt:z36.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z36.string(),nextPaymentAt:z36.string().nullable(),baseAmount:z36.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z36.object({totalCap:z36.number(),dailyCap:z36.number(),usedTotal:z36.number()}),CreditBalanceDTOSchema=z36.object({total:z36.number(),base:z36.number(),dailyBase:z36.number(),purchases:z36.number(),awards:z36.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z36.object({total:z36.number(),nearLimit:z36.boolean(),canChat:z36.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z36.object({dailyFreeAvailable:z36.number(),monthlyAvailable:z36.number(),purchasedAvailable:z36.number(),awardedAvailable:z36.number()}),ProjectDailyCreditAllowanceDTOSchema=z36.object({periodCap:z36.number(),dailyGrant:z36.number(),usedThisPeriod:z36.number(),remainingThisPeriod:z36.number()}),ProjectCreditBalanceDTOSchema=z36.object({projectId:z36.uuid(),organizationId:z36.string(),balance:z36.object({totalAvailable:z36.number(),nearLimit:z36.boolean(),canUseAi:z36.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z36.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z36.object({invoiceId:z36.string(),newBalance:z36.int(),creditCount:z36.int(),amountUsd:z36.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z36.object({url:z36.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 z37}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=z37.object({brand:z37.string(),last4:z37.string(),exp:z37.string(),isDefault:z37.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z38}from"zod";var FieldDefinitionSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_create_dto();init_response();FieldDefinitionSchema=z38.object({type:FieldTypeSchema,editable:z38.boolean().optional()}),ContentTypeI18nSchema=z38.object({enabled:z38.boolean()}).strict(),ContentTypeDTOSchema=z38.object({id:z38.string(),name:z38.string(),label:z38.string(),isSingleton:z38.boolean(),i18n:ContentTypeI18nSchema,fields:z38.record(z38.string(),z38.looseObject(FieldDefinitionSchema.shape)),createdAt:z38.string(),updatedAt:z38.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z38.object({contentTypes:z38.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z38.object({id:z38.string(),entryId:z38.string(),documentId:z38.string(),slug:z38.string(),locale:z38.string().optional(),createdAt:z38.string(),updatedAt:z38.string(),__fimo:z38.object({contentType:z38.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z38.object({data:z38.array(EntryDTOSchema),meta:z38.object({limit:z38.number(),offset:z38.number(),total:z38.number(),hasMore:z38.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z38.object({contentType:z38.string(),count:z38.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z38.object({counts:z38.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z38.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z38.array(EntryDTOSchema))}});import{z as z39}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=z39.object({id:z39.string(),name:z39.string()}),AssetDTOSchema=z39.object({id:z39.string(),name:z39.string(),type:AssetTypeSchema,originalFileName:z39.string().nullable(),parentId:z39.string().nullable(),mimeType:z39.string().nullable(),fileSize:z39.number().nullable(),url:z39.string().nullable(),storageKey:z39.string().nullable(),createdAt:z39.string(),updatedAt:z39.string(),altText:z39.string().nullable().optional(),caption:z39.string().nullable().optional(),aiCaption:z39.string().nullable().optional(),aiAltText:z39.string().nullable().optional(),aiTags:z39.array(z39.string()).nullable().optional(),aiPrimaryColor:z39.string().nullable().optional(),aiProcessingStatus:z39.string().nullable().optional(),width:z39.number().nullable().optional(),height:z39.number().nullable().optional(),path:z39.array(AssetPathItemSchema).optional(),hasChildren:z39.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z39.lazy(()=>z39.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z39.array(AssetDTOSchema))}});import{z as z40}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z40.object({key:z40.string(),value:z40.string().optional(),defaultValue:z40.string(),locale:z40.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z41}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=z41.object({id:z41.string(),name:z41.string(),type:z41.enum(["file","folder"]),path:z41.string(),children:z41.lazy(()=>z41.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z41.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z41.object({path:z41.string(),exists:z41.boolean(),type:z41.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z42}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=z42.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z42.object({items:z42.array(ProjectMessagePublicDTOSchema),nextCursor:z42.string().nullable()}),ChatDeletionDTOSchema=z42.object({success:z42.boolean(),deletedCount:z42.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z43}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=z43.object({url:z43.string().url(),key:z43.string(),size:z43.number(),contentType:z43.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z44}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=z44.object({canAccess:z44.boolean(),permissions:z44.record(z44.string(),z44.boolean()),role:z44.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z45}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:z45.string().trim().default(""),sort:z45.enum(["recent","name","relevance"]).default("recent"),category:z45.string().optional(),visibility:z45.enum(["public","private"]).optional()})}});import{z as z46}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=z46.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z46.enum(["fimo","external"]),PaymentStatusSchema=z46.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z46.object({id:z46.string().uuid(),domain:z46.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z46.boolean(),price:z46.number().int().nullable(),renewalPrice:z46.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z46.string().nullable(),failureReason:z46.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z46.object({domain:z46.string(),available:z46.boolean(),premium:z46.boolean(),price:z46.number().nullable(),renewalPrice:z46.number().nullable(),purchaseType:z46.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z46.object({domain:z46.string(),price:z46.number().nullable(),renewalPrice:z46.number().nullable(),premium:z46.boolean(),allowedYears:z46.array(z46.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z46.object({firstName:z46.string().max(100),lastName:z46.string().max(100),companyName:z46.string().max(100).optional(),address1:z46.string().max(255),address2:z46.string().max(255).optional(),city:z46.string().max(100),state:z46.string().max(100),zip:z46.string().max(20),country:z46.string().max(2),phone:z46.string().max(30),email:z46.union([z46.string().email().max(255),z46.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z46.object({firstName:z46.string().min(1).max(100),lastName:z46.string().min(1).max(100),companyName:z46.string().max(100).optional(),address1:z46.string().min(1).max(255),address2:z46.string().max(255).optional(),city:z46.string().min(1).max(100),state:z46.string().min(1).max(100),zip:z46.string().min(1).max(20),country:z46.string().min(1).max(2),phone:z46.string().min(1).max(30),email:z46.string().email().max(255)}),SearchDomainsRequestSchema=z46.object({keyword:z46.string().min(1).max(100),tldFilter:z46.array(z46.string()).optional()}),CheckAvailabilityRequestSchema=z46.object({domains:z46.array(z46.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=z46.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z46.object({domain:DomainNameSchema,years:z46.number().int().min(1).max(10).optional().default(3),autoRenew:z46.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z46.object({autoRenew:z46.boolean().optional()}),RenewDomainRequestSchema=z46.object({years:z46.number().int().min(1).max(10).optional().default(1),autoRenew:z46.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z46.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z46.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z46.object({verified:z46.boolean(),email:z46.string().nullable(),verifyBy:z46.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z47}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=z47.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=z47.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=z47.object({txtName:z47.string().nullable().optional(),txtValue:z47.string().nullable().optional(),httpUrl:z47.string().nullable().optional(),httpBody:z47.string().nullable().optional(),cname:z47.string().nullable().optional(),cnameTarget:z47.string().nullable().optional()}),SSLValidationErrorSchema=z47.object({message:z47.string()}),OwnershipVerificationSchema=z47.object({type:z47.string(),name:z47.string(),value:z47.string()}),ProjectDomainSSLDTOSchema=z47.object({status:z47.string(),method:z47.string().nullable(),type:z47.string().nullable(),validationRecords:z47.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z47.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z47.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z47.enum(["subdomain","apex"]),RedirectConfigSchema=z47.object({type:z47.literal("apex_to_www"),linkedDomainId:z47.string()}).nullable().optional(),ProjectDomainDTOSchema=z47.object({id:z47.string(),hostname:z47.string(),status:z47.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:OwnershipVerificationSchema.nullable().optional(),cnameTarget:z47.string(),scdCnameTarget:z47.string().optional(),dnsAutoConfigured:z47.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z47.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z47.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z47.object({hostname:z47.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:z47.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z47.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z47.object({available:z47.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z47.object({success:z47.boolean(),hostname:z47.string()}))}});import{z as z48}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=z48.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z48.object({available:z48.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z48.object({slug:z48.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z48.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z48.object({subdomain:z48.string(),subdomainUpdatedAt:z48.coerce.date()})),SubdomainSuggestionsQuerySchema=z48.object({base:z48.string().max(100).optional(),max:z48.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z48.object({suggestions:z48.array(z48.string())}))}});import{z as z49}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=z49.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z49.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=z49.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z49.number(),credits:z49.number().optional(),billingMode:z49.enum(["fimo-credits","provider-account"]).optional(),confidence:z49.enum(["exact","estimated","metered"]),basis:z49.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z50}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=z50.object({options:z50.record(z50.string(),z50.unknown()),name:z50.string().optional(),parentId:z50.string().nullable().optional(),altText:z50.string().optional(),caption:z50.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z50.string().min(1).optional(),model:z50.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=z50.object({jobId:z50.string(),status:z50.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z50.string().nullable().optional(),credits:z50.number().optional(),costUsd:z50.number().optional(),billingMode:z50.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z50.object({error:z50.string(),code:z50.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:z50.array(GenerationTaskIdSchema).optional(),availableModels:z50.array(z50.string()).optional(),issues:z50.array(z50.unknown()).optional()})}});import{z as z51}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=z51.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z51.object({name:z51.string(),key:z51.string(),description:z51.string(),type:FlagTypeSchema,required:z51.boolean(),defaultValue:z51.unknown().optional(),enumValues:z51.array(z51.string()).optional(),isArray:z51.boolean()}),AssetModelPriceSchema=z51.object({unitPrice:z51.number(),unit:z51.string(),confidence:z51.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z51.object({id:z51.string(),shortName:z51.string(),provider:z51.string(),source:z51.string(),modality:z51.enum(["image","video","audio"]),tags:z51.array(z51.string()),displayName:z51.string(),description:z51.string(),flags:z51.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z51.object({model:z51.string(),costUsd:z51.number(),credits:z51.number(),billingMode:z51.enum(["fimo-credits","provider-account"]),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z52}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=z52.object({tourId:z52.string(),version:z52.string(),status:z52.string(),completedAt:z52.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z52.array(UserTourDTOSchema))}});import{z as z53}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=z53.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z53.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z53.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z53.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z53.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z53.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z53.enum(["user","agent","system"]),SupportReportTagSchema=z53.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z53.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z53.object({organization:z53.object({id:z53.string().trim().min(1).max(255),name:z53.string().trim().max(240).optional()}),project:z53.object({id:z53.uuid(),name:z53.string().trim().max(240).optional(),createdAt:z53.coerce.date().optional()}).optional(),environment:z53.string().trim().max(255).optional(),clientVersion:z53.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z53.object({message:z53.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z53.string().trim().max(200).optional(),limit:z53.coerce.number().int().min(1).max(100).default(50),offset:z53.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z53.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z53.uuid().nullable().optional(),note:z53.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=z53.object({message:z53.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z53.object({kind:SupportReportLinkKindSchema,label:z53.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z53.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z53.object({kind:SupportReportActorKindSchema,id:z53.string().nullable(),name:z53.string().nullable()}),SupportReportLinkDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportLinkKindSchema,label:z53.string(),url:SupportReportHttpUrlSchema,externalId:z53.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportEventKindSchema,body:z53.string().nullable(),metadata:z53.record(z53.string(),z53.unknown()),actor:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z53.object({id:z53.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z53.array(z53.string()),source:SupportReportSourceSchema,message:z53.string(),reporter:z53.object({id:z53.string().nullable(),name:z53.string().nullable(),email:z53.string().nullable()}),organization:z53.object({id:z53.string().nullable(),name:z53.string()}),project:z53.object({id:z53.uuid().nullable(),name:z53.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z53.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z53.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z53.string().nullable(),deliveredAt:z53.coerce.date().nullable()}),duplicateOfReportId:z53.uuid().nullable(),resolvedAt:z53.coerce.date().nullable(),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z53.string().nullable(),clientVersion:z53.string().nullable(),links:z53.array(SupportReportLinkDTOSchema),events:z53.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z53.object({reports:z53.array(SupportReportSummaryDTOSchema),total:z53.number().int().nonnegative(),statusCounts:z53.object({new:z53.number().int().nonnegative(),in_progress:z53.number().int().nonnegative(),waiting:z53.number().int().nonnegative(),resolved:z53.number().int().nonnegative(),duplicate:z53.number().int().nonnegative(),irrelevant:z53.number().int().nonnegative(),ignored:z53.number().int().nonnegative()}),deliveryFailedCount:z53.number().int().nonnegative(),limit:z53.number().int().positive(),offset:z53.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z53.object({id:z53.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z53.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z54}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=z54.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z54.object({total:z54.number(),base:z54.number(),purchases:z54.number(),awards:z54.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z54.object({id:z54.string(),name:z54.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z54.object({type:z54.string(),brand:z54.string().nullable(),last4:z54.string().nullable(),expirationDate:z54.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z54.object({currency:z54.string(),nextPaymentAmount:z54.number().nullable(),nextPaymentAt:z54.string().nullable(),billingInterval:z54.string().nullable(),totalAmount:z54.number().nullable(),discountAmount:z54.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z54.object({id:z54.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z54.string().nullable(),currentPeriodEndsAt:z54.string().nullable(),renewsAt:z54.string().nullable(),cancelAt:z54.string().nullable(),renewAutomatically:z54.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z54.object({type:z54.enum(["low_balance","critical_balance","approaching_limit"]),message:z54.string(),estimatedPromptsRemaining:z54.number().nullable(),avgCostPerPrompt:z54.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z54.object({monthlyCredits:z54.number().nullable(),usedThisPeriod:z54.number(),remainingThisPeriod:z54.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z54.object({organizationId:z54.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z54.string().nullable(),tenureDays:z54.number().int().nonnegative(),capturedAt:z54.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z54.object({hasSubscription:z54.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z54.number().nullable(),alerts:z54.array(CreditAlertDTOSchema),portalUrl:z54.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z54.object({creditCount:z54.number().int().positive(),expiresAt:z54.string().datetime().nullable().optional(),message:z54.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z54.literal("free"),amountCents:z54.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z54.literal("purchase"),amountCents:z54.number().int().positive()}),CreditTopupRequestDTOSchema=z54.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z54.object({success:z54.boolean(),transactionId:z54.string().nullable(),newBalance:z54.number(),creditCount:z54.number(),type:z54.enum(["free","purchase"]),invoiceId:z54.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z55}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=z55.object({totalCredits:z55.number(),totalCostUsd:z55.number(),totalMessages:z55.number(),avgCostPerMessage:z55.number(),periodStart:z55.string().nullable(),periodEnd:z55.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z55.object({projectId:z55.string(),projectName:z55.string(),projectDisplayName:z55.string().nullable(),credits:z55.number(),costUsd:z55.number(),messages:z55.number(),percentage:z55.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z55.object({userId:z55.string(),userName:z55.string().nullable(),userEmail:z55.string().email().nullable(),credits:z55.number(),costUsd:z55.number(),messages:z55.number(),percentage:z55.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z55.object({date:z55.string(),credits:z55.number(),costUsd:z55.number(),messages:z55.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z55.object({userId:z55.string(),userName:z55.string().nullable(),userEmail:z55.string().email().nullable(),credits:z55.number(),costUsd:z55.number(),messages:z55.number(),percentage:z55.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z55.object({projectId:z55.string(),projectName:z55.string(),projectDisplayName:z55.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z55.array(UsageByUserForProjectDTOSchema),timeline:z55.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z55.object({summary:UsageSummaryDTOSchema,byProject:z55.array(UsageByProjectDTOSchema),byUser:z55.array(UsageByUserDTOSchema),timeline:z55.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z56}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=z56.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z56.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z56.object({startDate:z56.string().optional(),endDate:z56.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z56.coerce.number().int().positive().default(1),limit:z56.coerce.number().int().positive().max(100).default(20),sortBy:z56.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z56.string().optional()}),UsageOverviewSummaryDTOSchema=z56.object({totalCredits:z56.number(),totalCostUsd:z56.number(),totalMessages:z56.number(),avgCostPerMessage:z56.number(),avgCreditsPerMessage:z56.number(),periodStart:z56.string(),periodEnd:z56.string(),creditsChange:z56.number().nullable(),costChange:z56.number().nullable(),messagesChange:z56.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z56.object({date:z56.string(),credits:z56.number(),costUsd:z56.number(),messages:z56.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z56.object({organizationId:z56.string(),organizationName:z56.string(),credits:z56.number(),costUsd:z56.number(),messages:z56.number(),percentage:z56.number(),userCount:z56.number(),projectCount:z56.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z56.object({userId:z56.string(),userName:z56.string().nullable(),userEmail:z56.string().nullable(),userImage:z56.string().nullable(),organizationId:z56.string().nullable(),organizationName:z56.string().nullable(),credits:z56.number(),costUsd:z56.number(),messages:z56.number(),percentage:z56.number(),projectCount:z56.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z56.object({projectId:z56.string(),projectName:z56.string(),projectDisplayName:z56.string().nullable(),organizationId:z56.string(),organizationName:z56.string(),credits:z56.number(),costUsd:z56.number(),messages:z56.number(),percentage:z56.number(),userCount:z56.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z56.object({id:z56.string(),name:z56.string(),value:z56.number(),percentage:z56.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z56.object({day:z56.number(),hour:z56.number(),value:z56.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z56.object({summary:UsageOverviewSummaryDTOSchema,timeline:z56.array(UsageTimelinePointDTOSchema),topOrganizations:z56.array(OrganizationUsageRowDTOSchema),topUsers:z56.array(UserUsageRowDTOSchema),topProjects:z56.array(ProjectUsageRowDTOSchema),creditDistribution:z56.array(UsageDistributionItemDTOSchema),heatmap:z56.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z56.object({page:z56.number(),limit:z56.number(),totalItems:z56.number(),totalPages:z56.number(),hasMore:z56.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z56.object({organizations:z56.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z56.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z56.object({users:z56.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z56.string(),ownerName:z56.string().nullable(),ownerEmail:z56.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z56.object({projects:z56.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z56.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z56.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z56.object({credits:z56.number(),costUsd:z56.number(),messages:z56.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z56.object({id:z56.string(),name:z56.string(),createdAt:z56.string(),memberCount:z56.number(),projectCount:z56.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z56.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z56.object({id:z56.string(),name:z56.string().nullable(),email:z56.string(),image:z56.string().nullable(),createdAt:z56.string(),organizationCount:z56.number(),projectCount:z56.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z56.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z56.object({id:z56.string(),name:z56.string(),displayName:z56.string().nullable(),createdAt:z56.string(),organizationId:z56.string(),organizationName:z56.string(),ownerId:z56.string(),ownerName:z56.string().nullable(),ownerEmail:z56.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z56.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z57}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=z57.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z57.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z57.object({command:z57.string().min(1).max(1e4),cwd:z57.string().optional(),projectEnv:EnvSchema.optional(),env:z57.record(z57.string(),z57.string()).optional(),name:z57.string().optional(),waitForCompletion:z57.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z57.object({identifier:z57.string(),status:SandboxProcessStatusSchema,command:z57.string().optional(),startedAt:z57.string().optional(),exitCode:z57.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z57.object({processes:z57.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z57.object({processId:z57.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z57.object({success:z57.boolean(),message:z57.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z58}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_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_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit2(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit2(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit2(["status","--porcelain"],cwd)).length>0}async function cloneRepo2(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit2(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit2(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit2,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo2,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});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)}
438
+ `)}function renderCliAuthError(err,opts={}){console.error(formatCliAuthError(err,opts))}function formatShellArg(arg){return/^[A-Za-z0-9_/:=.,@%+-]+$/.test(arg)?arg:`'${arg.replace(/'/g,"'\\''")}'`}var init_auth_errors=__esm({"src/cli/utils/auth-errors.ts"(){init_api();init_auth();init_color();__name(isCliAuthError,"isCliAuthError");__name(rethrowCliAuthError,"rethrowCliAuthError");__name(retryCommand,"retryCommand");__name(formatCliAuthError,"formatCliAuthError");__name(renderCliAuthError,"renderCliAuthError");__name(formatShellArg,"formatShellArg")}});import{z as z7}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z7.ZodOptional||schema instanceof z7.ZodNullable||schema instanceof z7.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z7.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z7.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z7.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z7.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z7.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z7.ZodObject)return createObjectDTO(schema);if(schema instanceof z7.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z8}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z8.object({data:dataSchema}),"createResponseSchema")}});import{z as z9}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z9.object({page:z9.coerce.number().int().positive().default(1),limit:z9.coerce.number().int().positive().max(100).default(20)})}});import{z as z10}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z10.coerce.date(),positiveInt:z10.number().int().positive(),nonNegativeInt:z10.number().int().nonnegative()},BaseEntitySchema=z10.object({id:z10.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z10.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z10.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z10.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z10.enum(["public","private"]),ProjectStatusSchema=z10.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z10.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z10.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z10.enum(["owner","admin","member"]),AssetTypeSchema=z10.enum(["file","folder"]),TemplateCodeSchema=z10.enum(["Free","Premium"]),FieldTypeSchema=z10.enum(["string","richtext","media","number","boolean","date","json","reference"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as z11}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z11.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z12}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var ReferenceValueSchema,PolymorphicReferenceValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");ReferenceValueSchema=z12.preprocess(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({documentId:z12.uuid()}));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");PolymorphicReferenceValueSchema=z12.preprocess(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z12.object({contentType:z12.string().min(1),documentId:z12.uuid()}))}});import{z as z13}from"zod";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_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=z13.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z13.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z13.enum(AUDIT_ACTOR_KINDS)}});import{z as z14}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=z14.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=z14.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=z14.object({permissions:z14.array(OpsPermissionSchema).min(1),backendProfiles:z14.array(OpsBackendProfileSchema).min(1),enabled:z14.boolean().default(!0)}),OpsServiceTokenInputSchema=z14.object({name:z14.string().trim().min(1).max(120),permissions:z14.array(OpsPermissionSchema).min(1),backendProfiles:z14.array(OpsBackendProfileSchema).min(1),expiresAt:z14.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=z14.object({importanceReason:z14.string().trim().min(1).max(1e3),ownerUserId:z14.string().trim().min(1).nullable().optional(),framework:z14.string().trim().max(120).nullable().optional(),packageManager:z14.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z14.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z14.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z14.object({projectId:z14.uuid(),title:z14.string().trim().min(1).max(240),userReport:z14.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z14.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z14.string().trim().max(1e4).nullable().optional(),outcome:z14.string().trim().max(1e4).nullable().optional(),evidence:z14.array(z14.record(z14.string(),z14.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=z14.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z14.object({fingerprint:z14.string().trim().min(1).max(240),title:z14.string().trim().min(1).max(240),description:z14.string().trim().min(1).max(1e4),affectedVersions:z14.array(z14.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z14.array(z14.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z14.string().trim().min(1).max(64).nullable().optional(),workaround:z14.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z14.array(z14.string().trim().min(1).max(120)).max(100),detectionQueries:z14.array(z14.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=z14.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z14.object({changeReference:z14.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z14.string().trim().min(1).max(1e4),evidence:z14.array(z14.record(z14.string(),z14.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z14.object({recipientEmail:z14.email().optional(),subject:z14.string().trim().min(1).max(200).default("An update from Fimo"),message:z14.string().trim().min(1).max(5e3),locale:z14.string().trim().min(2).max(20),reason:z14.string().trim().min(1).max(1e3),acknowledgePolicy:z14.literal(!0)})}});import{z as z15}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:z15.string(),displayName:z15.string().nullable(),subdomain:z15.string().nullable().optional(),subdomainUpdatedAt:z15.date().nullable().optional(),organizationId:z15.string().nullable(),createdBy:z15.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z15.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z15.string(),thumbnailUrl:z15.string().nullable(),publishedThumbnailUrl:z15.string().nullable(),category:z15.string().nullable(),appUrl:z15.string().nullable(),lastPublishedAt:z15.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z15.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z15.object({id:z15.uuid(),name:z15.string(),displayName:z15.string().nullable(),thumbnailUrl:z15.string().nullable(),visibility:ProjectVisibilitySchema,category:z15.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z15.object({id:z15.string(),name:z15.string(),avatar:z15.string().nullable(),color:z15.object({bg:z15.string(),text:z15.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z15.object({path:z15.string(),content:z15.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z15.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z15.object({id:z15.string(),messageId:z15.string(),versionId:z15.string().nullable(),role:ProjectChatMessageRole,parts:z15.array(z15.any()),createdAt:z15.coerce.date()}),MessageUserMetadataSchema=z15.object({id:z15.string(),name:z15.string().nullable().optional(),image:z15.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z15.object({shortTitle:z15.string().optional(),questions:z15.array(z15.object({header:z15.string(),question:z15.string(),answer:z15.string(),selectedLabels:z15.array(z15.string()),freeText:z15.string(),skipped:z15.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z15.number(),metadata:z15.object({user:MessageUserMetadataSchema,changeManifest:z15.array(z15.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z15.object({id:z15.uuid(),versionId:z15.string(),projectId:z15.uuid(),commitHash:z15.string(),name:z15.string(),description:z15.string().nullable(),thumbnailUrl:z15.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z15.object({content:z15.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z15.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z15.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z15.object({success:z15.boolean(),message:z15.string().optional()})),ProjectPublicationStateDTOSchema=z15.object({isPublished:z15.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z15.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z15.object({success:z15.boolean(),message:z15.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z16}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=z16.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z16.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z16.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z16.string().nullable(),deletedAt:z16.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z16.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z16.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z16.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z16.object({surface:z16.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z16.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z16.number().int().nonnegative(),conflictCount:z16.number().int().nonnegative()}),EnvDiffResultSchema=z16.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z16.coerce.date(),surfaces:z16.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z17}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=z17.object({success:z17.literal(!0),downloadUrl:z17.string(),expiresAt:z17.string(),fileSize:z17.number(),duration:z17.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z17.object({success:z17.literal(!0),projectId:z17.string(),projectName:z17.string(),displayName:z17.string(),projectUrl:z17.string(),duration:z17.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z17.object({contentTypes:z17.number(),entries:z17.number(),assets:z17.number(),translations:z17.number(),forms:z17.number(),codeFiles:z17.number(),assetFiles:z17.number()}),ImportPreviewSurfaceDTOSchema=z17.object({name:z17.string(),included:z17.boolean(),count:z17.number().optional(),note:z17.string().optional()}),ImportPreviewDTOSchema=z17.object({projectName:z17.string(),displayName:z17.string().nullable(),visibility:z17.string().nullable(),category:z17.string().nullable(),exportedAt:z17.string(),version:z17.string(),envScope:z17.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z17.array(ImportPreviewSurfaceDTOSchema),fileSize:z17.number(),fileName:z17.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z17.object({success:z17.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z18}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=z18.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z18.object({type:z18.literal("manual")}),ScheduleTriggerSchema=z18.object({type:z18.literal("schedule"),cron:z18.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:z18.string().optional()}),WebhookTriggerSchema2=z18.object({type:z18.literal("webhook"),path:z18.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z18.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z19}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=z19.object({triggerIndices:z19.array(z19.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z19.object({triggerIndices:z19.array(z19.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z19.object({projectId:z19.uuid(),env:EnvSchema,agentName:z19.string().min(1),triggerIndex:z19.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z19.boolean(),lastFiredAt:z19.coerce.date().nullable(),webhookPath:z19.string().nullable(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z19.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z19.object({error:z19.literal("webhook_path_taken"),conflictAgent:z19.string(),path:z19.string()}),ManualRunRequestSchema=z19.object({args:z19.unknown().optional(),requestId:z19.string().min(1).max(128).optional()}),DispatchSkippedSchema=z19.object({skipped:z19.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z19.object({sessionId:z19.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z19.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z20}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=z20.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z20.object({token:z20.string().min(1),risk:CapabilityRiskTierSchema,description:z20.string()}),AgentSubAgentSummarySchema=z20.object({name:z20.string().min(1),grant:z20.enum(["inherit","explicit"]),effectiveCaps:z20.array(z20.string().min(1))}),AgentInstallSummaryDTOSchema=z20.object({agentName:z20.string().min(1),env:z20.string().min(1),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z20.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z20.array(CapabilitySummaryEntrySchema),criticalCapabilities:z20.array(CapabilitySummaryEntrySchema),subAgents:z20.array(AgentSubAgentSummarySchema),declaresDelegate:z20.boolean(),cycle:z20.array(z20.string()).nullable(),missingSubAgents:z20.array(z20.string()),warnings:z20.array(z20.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z21}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=z21.object({kind:TriggerKindSchema,summary:z21.string()}),AgentListItemActivationSchema=z21.object({triggerIndex:z21.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z21.string().min(1),active:z21.boolean()}),AgentListItemDTOSchema=z21.object({name:z21.string().min(1),description:z21.string().nullable(),goalFirstLine:z21.string().nullable(),declaredCapabilities:z21.array(CapabilitySummaryEntrySchema),triggers:z21.array(AgentListItemTriggerSchema),activations:z21.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z21.array(AgentListItemDTOSchema))}});import{z as z22}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=z22.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z22.object({cpuMs:z22.number().nonnegative().default(0),netBytes:z22.number().nonnegative().default(0),walltimeMs:z22.number().nonnegative().default(0),llmTokensIn:z22.number().nonnegative().optional(),llmTokensOut:z22.number().nonnegative().optional()}),AgentSessionDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),env:EnvSchema,agentName:z22.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z22.unknown().optional(),capabilities:z22.array(z22.string()).optional(),dataSources:z22.array(z22.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z22.string().nullable(),startedAt:z22.coerce.date().nullable(),finishedAt:z22.coerce.date().nullable(),cancelledAt:z22.coerce.date().nullable(),costUsd:z22.number().nonnegative(),costCeilingUsd:z22.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z22.boolean(),lastCheckpointId:z22.uuid().nullable(),branchEnvId:z22.uuid().nullable(),parentSessionId:z22.uuid().nullable(),terminalReason:z22.string().nullable(),errorMessage:z22.string().nullable(),report:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z22.object({id:z22.uuid(),sessionId:z22.uuid(),checkpointIdx:z22.number().int().nonnegative(),payloadRef:z22.string(),payloadSizeBytes:z22.number().int().nonnegative(),checksum:z22.string().length(64),createdAt:z22.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z22.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z22.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z22.object({session:AgentSessionDTOSchema,checkpoints:z22.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z22.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z22.object({reason:z22.string().min(1).max(120).optional()})}});import{z as z23}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=z23.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z23.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z23.object({id:z23.uuid(),envId:z23.uuid(),sessionId:z23.uuid().nullable(),skillName:z23.string().min(1),classification:AgentBranchClassificationSchema,rationale:z23.string().nullable(),summary:z23.string().nullable(),surfaceDeltas:z23.record(z23.string(),z23.unknown()),createdAt:z23.coerce.date(),decidedAt:z23.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z23.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z23.object({path:z23.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z23.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z23.object({code:z23.literal("merge_conflict"),message:z23.string(),conflicts:z23.record(z23.string(),z23.number().int().nonnegative())})}});import{z as z24}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=z24.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z24.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z24.enum(["secret_text"]),IntegrationCredentialUsageSchema=z24.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z24.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z24.object({mode:IntegrationAuthModeSchema,label:z24.string().min(1),description:z24.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z24.object({id:z24.string().min(1),label:z24.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z24.boolean()}),IntegrationToolDefinitionDTOSchema=z24.object({key:z24.string().min(1),name:z24.string().min(1),description:z24.string().min(1)}),IntegrationRecipeDTOSchema=z24.object({title:z24.string().min(1),description:z24.string().min(1),command:z24.string().min(1).optional()}),IntegrationInfoDTOSchema=z24.object({key:z24.string().min(1),name:z24.string().min(1),summary:z24.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z24.array(IntegrationAuthModeDTOSchema),credentials:z24.array(IntegrationCredentialDefinitionDTOSchema),tools:z24.array(IntegrationToolDefinitionDTOSchema),recipes:z24.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z24.object({projectId:z24.uuid(),integrationKey:z24.string().min(1),installed:z24.boolean(),enabled:z24.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z24.string().nullable(),connectionId:z24.uuid().nullable().optional(),connectionAlias:z24.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z24.array(z24.string()),installedAt:z24.coerce.date().nullable(),updatedAt:z24.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),integrationKey:z24.string().min(1),enabled:z24.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z24.string(),connectionId:z24.uuid().nullable().optional(),connectionAlias:z24.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z24.array(z24.string()),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z24.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z24.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z24.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z24.object({value:z24.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z24.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z24.object({id:z24.uuid(),organizationId:z24.string().min(1),integrationKey:z24.string().min(1),alias:z24.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z24.string().min(1),externalAccountName:z24.string().nullable(),externalBotUserId:z24.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z24.array(z24.string()),connectedAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z24.object({alias:z24.string().min(1).max(120).optional(),token:z24.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z24.object({integrationKey:z24.string().min(1),connectUrl:z24.string().url(),expiresAt:z24.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z24.object({ref:z24.string().min(1),connectionAlias:z24.string().min(1).optional(),agentName:z24.string().min(1).max(160).nullable().optional(),force:z24.boolean().optional()}),ProjectChannelBindingDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),integrationKey:z24.string().min(1),connectionId:z24.uuid(),externalWorkspaceId:z24.string().min(1),externalChannelId:z24.string().min(1),externalChannelName:z24.string().nullable(),agentName:z24.string().nullable(),enabled:z24.boolean(),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z24.object({markdown:z24.boolean().optional(),summary:z24.boolean().optional(),links:z24.boolean().optional(),images:z24.boolean().optional(),html:z24.union([z24.literal("cleaned"),z24.literal("raw"),z24.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z24.object({url:z24.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional(),waitForMs:z24.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z24.object({query:z24.string().min(1),maxResults:z24.number().int().positive().max(20).optional(),timeoutMs:z24.number().int().positive().max(12e4).optional()}),FirecrawlMapToolInputSchema=z24.object({url:z24.string().url(),search:z24.string().min(1).optional(),limit:z24.number().int().positive().max(200).optional(),includeSubdomains:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z24.object({url:z24.string().url(),limit:z24.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z24.object({text:z24.string().min(1).max(200).optional(),cron:z24.string().min(1).max(120).optional(),timezone:z24.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z24.object({type:z24.enum(["scrape","crawl"]).default("scrape"),urls:z24.array(z24.string().url()).min(1).max(50),scrapeOptions:z24.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z24.boolean().optional(),timeoutMs:z24.number().int().positive().max(12e4).optional(),waitForMs:z24.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z24.object({name:z24.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z24.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z24.string().min(1).max(2e3).optional(),judgeEnabled:z24.boolean().optional(),retentionDays:z24.number().int().min(1).max(365).optional(),notification:z24.object({email:z24.object({enabled:z24.boolean().default(!0),recipients:z24.array(z24.string().email()).min(1).max(20),includeDiffs:z24.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z24.object({monitorId:z24.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z24.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z24.object({connectionAlias:z24.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z24.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.list"),input:z24.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z24.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z24.object({provider:z24.string().min(1),providerCredits:z24.number().nonnegative().optional(),providerCostUsd:z24.number().nonnegative().optional(),requests:z24.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z24.object({credits:z24.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z24.object({url:z24.string(),provider:z24.literal("firecrawl"),title:z24.string().optional(),statusCode:z24.number().optional(),markdown:z24.string().optional(),summary:z24.string().optional(),links:z24.array(z24.string()).optional(),images:z24.array(z24.string()).optional(),html:z24.string().optional(),warning:z24.string().optional()}),FirecrawlSearchToolOutputSchema=z24.object({query:z24.string(),provider:z24.literal("firecrawl"),results:z24.array(z24.object({title:z24.string(),url:z24.string(),snippet:z24.string().optional(),content:z24.string().optional(),score:z24.number().optional(),publishedAt:z24.string().optional()}))}),FirecrawlMapToolOutputSchema=z24.object({url:z24.string(),provider:z24.literal("firecrawl"),count:z24.number(),links:z24.array(z24.object({url:z24.string(),title:z24.string().optional(),description:z24.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z24.object({url:z24.string(),provider:z24.literal("firecrawl"),total:z24.number(),pages:z24.array(z24.object({url:z24.string(),title:z24.string().optional(),statusCode:z24.number().optional(),markdown:z24.string().optional(),summary:z24.string().optional(),links:z24.array(z24.string()).optional(),images:z24.array(z24.string()).optional(),html:z24.string().optional(),warning:z24.string().optional()})),warning:z24.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z24.object({cron:z24.string().optional(),text:z24.string().optional(),timezone:z24.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z24.object({id:z24.string().optional(),urls:z24.array(z24.string()).optional(),scrapeOptions:z24.record(z24.string(),z24.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z24.object({id:z24.string(),name:z24.string(),status:z24.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z24.string().nullable().optional(),lastRunAt:z24.string().nullable().optional(),currentCheckId:z24.string().nullable().optional(),targets:z24.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z24.string().nullable().optional(),judgeEnabled:z24.boolean().optional(),estimatedCreditsPerMonth:z24.number().optional(),createdAt:z24.string().optional(),updatedAt:z24.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z24.object({id:z24.string(),monitorId:z24.string(),scheduledFor:z24.string().nullable().optional(),startedAt:z24.string().nullable().optional(),finishedAt:z24.string().nullable().optional(),estimatedCredits:z24.number().optional(),reservedCredits:z24.number().optional(),actualCredits:z24.number().optional(),billingStatus:z24.string().nullable().optional(),summary:z24.object({totalPages:z24.number().optional(),same:z24.number().optional(),changed:z24.number().optional(),new:z24.number().optional(),removed:z24.number().optional(),error:z24.number().optional()}).passthrough().optional(),error:z24.string().nullable().optional(),createdAt:z24.string().optional(),updatedAt:z24.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitors:z24.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitorId:z24.string(),deleted:z24.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitorId:z24.string(),checks:z24.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z24.object({provider:z24.literal("firecrawl"),monitorId:z24.string(),check:FirecrawlMonitorCheckOutputSchema,next:z24.string().optional()}),FirecrawlToolKeySchema=z24.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z24.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z24.object({projectId:z24.uuid(),integrationKey:z24.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z24.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z24.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z24.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z24.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z24.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z24.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z24.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z24.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z24.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z24.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 z25}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=z25.enum(["ok","failed"]),ProjectScheduleDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),env:z25.string().min(1),name:z25.string().min(1),cron:z25.string().min(1),command:z25.string().min(1),enabled:z25.boolean(),lastRunAt:z25.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z25.string().nullable(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z25.object({name:z25.string().min(1).max(120),cron:z25.string().min(1).max(120),command:z25.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z25.array(ProjectScheduleDTOSchema))}});import{z as z26}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=z26.object({id:z26.uuid(),occurredAt:z26.coerce.date(),projectId:z26.uuid().nullable(),env:z26.string().nullable(),actor:z26.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z26.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z26.unknown().optional(),ipAddress:z26.string().nullable().optional(),userAgent:z26.string().nullable().optional(),error:z26.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z26.object({rows:z26.array(AuditLogRowDTOSchema),nextCursor:z26.string().nullable()})),AuditLogQuerySchema=z26.object({env:z26.string().optional(),action:AuditActionSchema.optional(),actor:z26.string().optional(),from:z26.coerce.date().optional(),to:z26.coerce.date().optional(),limit:z26.coerce.number().int().min(1).max(200).optional(),cursor:z26.string().optional()})}});import{z as z27}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,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=z27.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z27.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z27.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z27.object({verb:SurfaceDeltaVerbSchema,key:z27.string(),detail:z27.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z27.record(z27.string(),z27.unknown()).optional()}),PerSurfaceDeltaSchema=z27.object({surface:SurfaceNameSchema,status:z27.enum(["ok","timed_out","failed","unchanged"]),durationMs:z27.number().int().nonnegative().optional(),changedCount:z27.number().int().nonnegative(),conflictCount:z27.number().int().nonnegative(),items:z27.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z27.boolean().optional(),error:z27.string().optional()}),CrossSurfaceFindingSchema=z27.object({id:z27.string(),kind:z27.string(),description:z27.string(),severity:z27.enum(["warning","error"]),source:z27.object({surface:SurfaceNameSchema,key:z27.string()}),target:z27.object({surface:SurfaceNameSchema,key:z27.string()}),actions:z27.array(z27.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z27.object({env:EnvSchema,vs:EnvSchema,syncState:z27.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),agents:z27.array(z27.object({id:z27.string(),name:z27.string(),status:z27.enum(["active","paused","failed"]),lastRunAt:z27.coerce.date().nullable()})).optional(),crossSurface:z27.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z27.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z27.coerce.date(),surfaces:z27.array(PerSurfaceDeltaSchema),crossSurface:z27.array(CrossSurfaceFindingSchema).optional(),fingerprint:z27.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z27.object({path:z27.string(),state:z27.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z27.string(),additions:z27.number().int().nonnegative(),deletions:z27.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z27.object({oid:z27.string().optional(),content:z27.string().optional(),truncated:z27.boolean(),binary:z27.boolean()}),CodeConflictDetailSchema=z27.object({path:z27.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z27.string(),targetTipSha:z27.string(),mergeBaseSha:z27.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z27.object({id:z27.string(),slug:z27.string(),contentType:z27.string(),data:z27.record(z27.string(),z27.unknown()),updatedAt:z27.coerce.date()}),ContentRowDiffSchema=z27.object({collection:z27.string(),rowId:z27.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z27.object({name:z27.string(),label:z27.string(),isSingleton:z27.boolean(),fields:z27.record(z27.string(),z27.unknown())}),SchemaTypeDiffSchema=z27.object({typeName:z27.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z27.object({id:z27.string(),name:z27.string(),type:z27.enum(["file","folder"]),mimeType:z27.string().nullable(),storageKey:z27.string().nullable(),url:z27.string().nullable(),fileSize:z27.number().nullable(),width:z27.number().nullable(),height:z27.number().nullable(),altText:z27.string().nullable(),caption:z27.string().nullable(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AssetDiffSchema=z27.object({assetId:z27.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z27.object({locale:z27.string(),key:z27.string(),parent:z27.string().nullable(),child:z27.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z27.object({formName:z27.string(),label:z27.string().nullable(),schemaFingerprint:z27.string(),fields:z27.record(z27.string(),z27.unknown()),settings:z27.record(z27.string(),z27.unknown()).optional()}),FormSchemaDiffSchema=z27.object({formName:z27.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z27.object({agentName:z27.string(),triggerIndex:z27.number().int().nonnegative(),triggerKind:z27.string(),triggerSpec:z27.record(z27.string(),z27.unknown()),enabled:z27.boolean(),emailRecipients:z27.array(z27.string()).nullable(),qstashScheduleId:z27.string().nullable()}),ActivationDiffSchema=z27.object({agentName:z27.string(),triggerIndex:z27.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),ConflictSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),kind:z27.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity"]).optional(),description:z27.string(),parentValue:z27.unknown().optional(),childValue:z27.unknown().optional(),conflictingFields:z27.array(z27.string()).optional(),code:z27.object({path:z27.string(),unresolvable:z27.boolean().optional(),reason:z27.string().optional()}).optional()}),FieldPickSchema=z27.object({field:z27.string(),choice:z27.enum(["parent","child","pick","ai-pick"]),pickedValue:z27.unknown().optional(),aiSessionId:z27.string().optional()}),ConflictResolutionSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),choice:z27.enum(["parent","child","pick"]),pickedValue:z27.unknown().optional(),fieldPicks:z27.array(FieldPickSchema).optional()}),MergeResultSchema=z27.object({ok:z27.boolean(),mergeId:z27.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z27.array(z27.object({surface:SurfaceNameSchema,count:z27.number().int().nonnegative()})),conflicts:z27.array(ConflictSchema).optional(),summary:z27.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z27.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z27.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z27.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z27.boolean().optional()}),ResolvedStrategySchema=z27.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z27.boolean()}),MergeRequestSchema=z27.object({from:EnvSchema,allowDirectMerge:z27.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z27.object({mergeId:z27.string().uuid(),streamUrl:z27.string(),strategy:ResolvedStrategySchema,acceptedAt:z27.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z27.object({mergeId:z27.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z27.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z27.array(ConflictSchema),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedBy:z27.string().nullable(),lastEditedAt:z27.coerce.date().nullable(),initiator:z27.object({userId:z27.string().nullable(),role:z27.string().nullable(),agentName:z27.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z27.object({resolutions:z27.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z27.object({mergeId:z27.string().uuid(),draftResolutions:z27.array(ConflictResolutionSchema),lastEditedAt:z27.coerce.date(),lastEditedBy:z27.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z27.object({mergeId:z27.string().uuid(),resolutions:z27.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z27.object({mergeId:z27.string().uuid()}),PublishReleaseRequestSchema=z27.object({version:z27.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z27.string().max(2e4).optional()}),PublishReleaseResultSchema=z27.object({releaseTag:z27.string(),sha:z27.string(),publishedAt:z27.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z28}from"zod";var 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=z28.object({surface:SurfaceNameSchema,key:z28.string(),label:z28.string()}),InlineSchema=z28.object({text:z28.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z28.discriminatedUnion("type",[z28.object({type:z28.literal("paragraph"),content:z28.array(InlineSchema).max(24)}),z28.object({type:z28.literal("preview"),ref:DiffRefSchema,caption:z28.string().optional()}),z28.object({type:z28.literal("code"),code:z28.string(),lang:z28.string().optional(),caption:z28.string().optional()}),z28.object({type:z28.literal("risk"),level:z28.enum(["warning","error"]),content:z28.array(InlineSchema).max(24)}),z28.object({type:z28.literal("list"),items:z28.array(z28.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z28.object({headline:z28.string(),blocks:z28.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z28.object({summary:EnvDiffSummarySchema,fingerprint:z28.string(),generatedAt:z28.coerce.date(),cached:z28.boolean().optional(),credits:z28.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z29}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=z29.object({date:z29.string(),visitors:z29.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z29.object({key:z29.string(),visitors:z29.number().int().nonnegative(),pageviews:z29.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z29.object({path:z29.string(),pageName:z29.string().nullable().optional(),visitors:z29.number().int().nonnegative(),pageviews:z29.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z29.object({preset:z29.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z29.string(),requestedTo:z29.string(),effectiveFrom:z29.string(),effectiveTo:z29.string(),isRetentionLimited:z29.boolean(),groupBy:z29.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z29.object({date:z29.string(),content:z29.string(),updatedAt:z29.string(),updatedByUserId:z29.string()}),ProjectPageviewAnalyticsDTOSchema=z29.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z29.number().int().nonnegative(),pageviews:z29.number().int().nonnegative(),bounceRate:z29.number().min(0).max(100),viewsPerVisit:z29.number().nonnegative(),averageVisitDurationSeconds:z29.number().nonnegative(),visitorsSeries:z29.array(ProjectDailyVisitorsDTOSchema),topPages:z29.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z29.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z29.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z30}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=z30.object({id:z30.string(),email:z30.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z30.coerce.date(),createdAt:z30.coerce.date(),inviterUserId:z30.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z30.object({id:z30.string(),token:z30.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z30.object({success:z30.boolean(),projectId:z30.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z31}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=z31.object({id:z31.string(),name:z31.string(),image:z31.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z31.object({count:z31.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z31.object({counts:z31.object({signed_up:z31.int(),activated:z31.int()}),credits:z31.object({total:z31.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z31.email(),emailVerified:z31.boolean(),createdAt:z31.coerce.date(),updatedAt:z31.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z32}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=z32.object({id:z32.string(),principalType:ProjectPrincipalTypeSchema,principalId:z32.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z32.coerce.date(),expiresAt:z32.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z32.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z32.record(z32.string(),z32.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z32.object({access:z32.array(ProjectAccessItemDTOSchema),invites:z32.array(ProjectInviteDTOSchema),organization:z32.object({name:z32.string().nullable(),logo:z32.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z32.object({success:z32.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z32.object({success:z32.boolean(),projectId:z32.uuid()}))}});import{z as z33}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=z33.object({publicationStatus:PublicationStatusSchema,appUrl:z33.string().nullable(),lastPublishedAt:z33.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z34}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=z34.object({url:z34.url(),expiresAt:z34.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z34.discriminatedUnion("source",[z34.object({source:z34.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z34.null()}),z34.object({source:z34.literal("dev"),artifact:z34.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z35}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:z35.string(),slug:z35.string().nullable(),logo:z35.string().nullable(),metadata:z35.record(z35.string(),z35.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z35.object({id:z35.string(),name:z35.string(),email:z35.email(),image:z35.string().nullable()}),OrganizationMemberDTOSchema=z35.object({id:z35.string(),userId:z35.string(),organizationId:z35.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z35.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z36}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=z36.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z36.object({reason:CancellationReasonCodeSchema,details:z36.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z36.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z36.object({included:z36.number().optional(),unitPrice:z36.number().optional(),dailyCap:z36.number().nullable().optional()}),EntitlementsDTOSchema=z36.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z36.object({retentionDays:z36.number().int().positive(),canUseExtendedDateRanges:z36.boolean()}).optional(),members:z36.object({canInvite:z36.boolean(),maxMembers:z36.number().int().positive().nullable()}).optional(),projects:z36.object({canCreatePrivateProjects:z36.boolean(),maxPrivateProjects:z36.number().int().positive().nullable()}).optional(),domains:z36.object({canUseCustomDomains:z36.boolean(),maxDomains:z36.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z36.object({id:z36.string(),external_id:z36.string(),customerId:z36.string(),planId:z36.string(),planCode:TemplateCodeSchema,currentPeriod:z36.object({start:z36.string(),end:z36.string().nullable()}),cancelAt:z36.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z36.string(),nextPaymentAt:z36.string().nullable(),baseAmount:z36.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z36.object({totalCap:z36.number(),dailyCap:z36.number(),usedTotal:z36.number()}),CreditBalanceDTOSchema=z36.object({total:z36.number(),base:z36.number(),dailyBase:z36.number(),purchases:z36.number(),awards:z36.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z36.object({total:z36.number(),nearLimit:z36.boolean(),canChat:z36.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z36.object({dailyFreeAvailable:z36.number(),monthlyAvailable:z36.number(),purchasedAvailable:z36.number(),awardedAvailable:z36.number()}),ProjectDailyCreditAllowanceDTOSchema=z36.object({periodCap:z36.number(),dailyGrant:z36.number(),usedThisPeriod:z36.number(),remainingThisPeriod:z36.number()}),ProjectCreditBalanceDTOSchema=z36.object({projectId:z36.uuid(),organizationId:z36.string(),balance:z36.object({totalAvailable:z36.number(),nearLimit:z36.boolean(),canUseAi:z36.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z36.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z36.object({invoiceId:z36.string(),newBalance:z36.int(),creditCount:z36.int(),amountUsd:z36.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z36.object({url:z36.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 z37}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=z37.object({brand:z37.string(),last4:z37.string(),exp:z37.string(),isDefault:z37.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z38}from"zod";var FieldDefinitionSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_create_dto();init_response();FieldDefinitionSchema=z38.object({type:FieldTypeSchema,editable:z38.boolean().optional()}),ContentTypeI18nSchema=z38.object({enabled:z38.boolean()}).strict(),ContentTypeDTOSchema=z38.object({id:z38.string(),name:z38.string(),label:z38.string(),isSingleton:z38.boolean(),i18n:ContentTypeI18nSchema,fields:z38.record(z38.string(),z38.looseObject(FieldDefinitionSchema.shape)),createdAt:z38.string(),updatedAt:z38.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z38.object({contentTypes:z38.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z38.object({id:z38.string(),entryId:z38.string(),documentId:z38.string(),slug:z38.string(),locale:z38.string().optional(),createdAt:z38.string(),updatedAt:z38.string(),__fimo:z38.object({contentType:z38.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z38.object({data:z38.array(EntryDTOSchema),meta:z38.object({limit:z38.number(),offset:z38.number(),total:z38.number(),hasMore:z38.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z38.object({contentType:z38.string(),count:z38.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z38.object({counts:z38.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z38.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z38.array(EntryDTOSchema))}});import{z as z39}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=z39.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z39.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z39.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z39.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z39.object({field:CmsFieldNameSchema,direction:z39.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z39.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z39.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z39.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z39.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z39.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z40}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=z40.object({id:z40.string(),name:z40.string()}),AssetDTOSchema=z40.object({id:z40.string(),name:z40.string(),type:AssetTypeSchema,originalFileName:z40.string().nullable(),parentId:z40.string().nullable(),mimeType:z40.string().nullable(),fileSize:z40.number().nullable(),url:z40.string().nullable(),storageKey:z40.string().nullable(),createdAt:z40.string(),updatedAt:z40.string(),altText:z40.string().nullable().optional(),caption:z40.string().nullable().optional(),aiCaption:z40.string().nullable().optional(),aiAltText:z40.string().nullable().optional(),aiTags:z40.array(z40.string()).nullable().optional(),aiPrimaryColor:z40.string().nullable().optional(),aiProcessingStatus:z40.string().nullable().optional(),width:z40.number().nullable().optional(),height:z40.number().nullable().optional(),path:z40.array(AssetPathItemSchema).optional(),hasChildren:z40.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z40.lazy(()=>z40.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z40.array(AssetDTOSchema))}});import{z as z41}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z41.object({key:z41.string(),value:z41.string().optional(),defaultValue:z41.string(),locale:z41.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z42}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=z42.object({id:z42.string(),name:z42.string(),type:z42.enum(["file","folder"]),path:z42.string(),children:z42.lazy(()=>z42.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z42.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z42.object({path:z42.string(),exists:z42.boolean(),type:z42.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z43}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=z43.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z43.object({items:z43.array(ProjectMessagePublicDTOSchema),nextCursor:z43.string().nullable()}),ChatDeletionDTOSchema=z43.object({success:z43.boolean(),deletedCount:z43.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z44}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=z44.object({url:z44.string().url(),key:z44.string(),size:z44.number(),contentType:z44.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z45}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=z45.object({canAccess:z45.boolean(),permissions:z45.record(z45.string(),z45.boolean()),role:z45.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z46}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:z46.string().trim().default(""),sort:z46.enum(["recent","name","relevance"]).default("recent"),category:z46.string().optional(),visibility:z46.enum(["public","private"]).optional()})}});import{z as z47}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=z47.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z47.enum(["fimo","external"]),PaymentStatusSchema=z47.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z47.object({id:z47.string().uuid(),domain:z47.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z47.boolean(),price:z47.number().int().nullable(),renewalPrice:z47.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z47.string().nullable(),failureReason:z47.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z47.object({domain:z47.string(),available:z47.boolean(),premium:z47.boolean(),price:z47.number().nullable(),renewalPrice:z47.number().nullable(),purchaseType:z47.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z47.object({domain:z47.string(),price:z47.number().nullable(),renewalPrice:z47.number().nullable(),premium:z47.boolean(),allowedYears:z47.array(z47.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z47.object({firstName:z47.string().max(100),lastName:z47.string().max(100),companyName:z47.string().max(100).optional(),address1:z47.string().max(255),address2:z47.string().max(255).optional(),city:z47.string().max(100),state:z47.string().max(100),zip:z47.string().max(20),country:z47.string().max(2),phone:z47.string().max(30),email:z47.union([z47.string().email().max(255),z47.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z47.object({firstName:z47.string().min(1).max(100),lastName:z47.string().min(1).max(100),companyName:z47.string().max(100).optional(),address1:z47.string().min(1).max(255),address2:z47.string().max(255).optional(),city:z47.string().min(1).max(100),state:z47.string().min(1).max(100),zip:z47.string().min(1).max(20),country:z47.string().min(1).max(2),phone:z47.string().min(1).max(30),email:z47.string().email().max(255)}),SearchDomainsRequestSchema=z47.object({keyword:z47.string().min(1).max(100),tldFilter:z47.array(z47.string()).optional()}),CheckAvailabilityRequestSchema=z47.object({domains:z47.array(z47.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=z47.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z47.object({domain:DomainNameSchema,years:z47.number().int().min(1).max(10).optional().default(3),autoRenew:z47.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z47.object({autoRenew:z47.boolean().optional()}),RenewDomainRequestSchema=z47.object({years:z47.number().int().min(1).max(10).optional().default(1),autoRenew:z47.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z47.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z47.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z47.object({verified:z47.boolean(),email:z47.string().nullable(),verifyBy:z47.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z48}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=z48.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=z48.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=z48.object({txtName:z48.string().nullable().optional(),txtValue:z48.string().nullable().optional(),httpUrl:z48.string().nullable().optional(),httpBody:z48.string().nullable().optional(),cname:z48.string().nullable().optional(),cnameTarget:z48.string().nullable().optional()}),SSLValidationErrorSchema=z48.object({message:z48.string()}),OwnershipVerificationSchema=z48.object({type:z48.string(),name:z48.string(),value:z48.string()}),ProjectDomainSSLDTOSchema=z48.object({status:z48.string(),method:z48.string().nullable(),type:z48.string().nullable(),validationRecords:z48.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z48.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z48.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z48.enum(["subdomain","apex"]),RedirectConfigSchema=z48.object({type:z48.literal("apex_to_www"),linkedDomainId:z48.string()}).nullable().optional(),ProjectDomainDTOSchema=z48.object({id:z48.string(),hostname:z48.string(),status:z48.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z48.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z48.string(),scdCnameTarget:z48.string().optional(),apexTargets:z48.array(z48.string()),dnsAutoConfigured:z48.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z48.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z48.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z48.object({hostname:z48.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:z48.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z48.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z48.object({available:z48.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z48.object({success:z48.boolean(),hostname:z48.string()}))}});import{z as z49}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=z49.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z49.object({slug:z49.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z49.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z49.object({subdomain:z49.string(),subdomainUpdatedAt:z49.coerce.date()})),SubdomainSuggestionsQuerySchema=z49.object({base:z49.string().max(100).optional(),max:z49.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z49.object({suggestions:z49.array(z49.string())}))}});import{z as z50}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=z50.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z50.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=z50.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z50.number(),credits:z50.number().optional(),billingMode:z50.enum(["fimo-credits","provider-account"]).optional(),confidence:z50.enum(["exact","estimated","metered"]),basis:z50.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z51}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=z51.object({options:z51.record(z51.string(),z51.unknown()),name:z51.string().optional(),parentId:z51.string().nullable().optional(),altText:z51.string().optional(),caption:z51.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z51.string().min(1).optional(),model:z51.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=z51.object({jobId:z51.string(),status:z51.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z51.string().nullable().optional(),credits:z51.number().optional(),costUsd:z51.number().optional(),billingMode:z51.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z51.object({error:z51.string(),code:z51.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:z51.array(GenerationTaskIdSchema).optional(),availableModels:z51.array(z51.string()).optional(),issues:z51.array(z51.unknown()).optional()})}});import{z as z52}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=z52.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z52.object({name:z52.string(),key:z52.string(),description:z52.string(),type:FlagTypeSchema,required:z52.boolean(),defaultValue:z52.unknown().optional(),enumValues:z52.array(z52.string()).optional(),isArray:z52.boolean()}),AssetModelPriceSchema=z52.object({unitPrice:z52.number(),unit:z52.string(),confidence:z52.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z52.object({id:z52.string(),shortName:z52.string(),provider:z52.string(),source:z52.string(),modality:z52.enum(["image","video","audio"]),tags:z52.array(z52.string()),displayName:z52.string(),description:z52.string(),flags:z52.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z52.object({model:z52.string(),costUsd:z52.number(),credits:z52.number(),billingMode:z52.enum(["fimo-credits","provider-account"]),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z53}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=z53.object({tourId:z53.string(),version:z53.string(),status:z53.string(),completedAt:z53.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z53.array(UserTourDTOSchema))}});import{z as z54}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=z54.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z54.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z54.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z54.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z54.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z54.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z54.enum(["user","agent","system"]),SupportReportTagSchema=z54.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z54.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z54.object({organization:z54.object({id:z54.string().trim().min(1).max(255),name:z54.string().trim().max(240).optional()}),project:z54.object({id:z54.uuid(),name:z54.string().trim().max(240).optional(),createdAt:z54.coerce.date().optional()}).optional(),environment:z54.string().trim().max(255).optional(),clientVersion:z54.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z54.object({message:z54.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z54.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z54.string().trim().max(200).optional(),limit:z54.coerce.number().int().min(1).max(100).default(50),offset:z54.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z54.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z54.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z54.uuid().nullable().optional(),note:z54.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=z54.object({message:z54.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z54.object({kind:SupportReportLinkKindSchema,label:z54.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z54.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z54.object({kind:SupportReportActorKindSchema,id:z54.string().nullable(),name:z54.string().nullable()}),SupportReportLinkDTOSchema=z54.object({id:z54.uuid(),kind:SupportReportLinkKindSchema,label:z54.string(),url:SupportReportHttpUrlSchema,externalId:z54.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z54.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z54.object({id:z54.uuid(),kind:SupportReportEventKindSchema,body:z54.string().nullable(),metadata:z54.record(z54.string(),z54.unknown()),actor:SupportReportActorDTOSchema,createdAt:z54.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z54.object({id:z54.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z54.array(z54.string()),source:SupportReportSourceSchema,message:z54.string(),reporter:z54.object({id:z54.string().nullable(),name:z54.string().nullable(),email:z54.string().nullable()}),organization:z54.object({id:z54.string().nullable(),name:z54.string()}),project:z54.object({id:z54.uuid().nullable(),name:z54.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z54.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z54.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z54.string().nullable(),deliveredAt:z54.coerce.date().nullable()}),duplicateOfReportId:z54.uuid().nullable(),resolvedAt:z54.coerce.date().nullable(),createdAt:z54.coerce.date(),updatedAt:z54.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z54.string().nullable(),clientVersion:z54.string().nullable(),links:z54.array(SupportReportLinkDTOSchema),events:z54.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z54.object({reports:z54.array(SupportReportSummaryDTOSchema),total:z54.number().int().nonnegative(),statusCounts:z54.object({new:z54.number().int().nonnegative(),in_progress:z54.number().int().nonnegative(),waiting:z54.number().int().nonnegative(),resolved:z54.number().int().nonnegative(),duplicate:z54.number().int().nonnegative(),irrelevant:z54.number().int().nonnegative(),ignored:z54.number().int().nonnegative()}),deliveryFailedCount:z54.number().int().nonnegative(),limit:z54.number().int().positive(),offset:z54.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z54.object({id:z54.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z54.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z55}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=z55.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z55.object({total:z55.number(),base:z55.number(),purchases:z55.number(),awards:z55.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z55.object({id:z55.string(),name:z55.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z55.object({type:z55.string(),brand:z55.string().nullable(),last4:z55.string().nullable(),expirationDate:z55.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z55.object({currency:z55.string(),nextPaymentAmount:z55.number().nullable(),nextPaymentAt:z55.string().nullable(),billingInterval:z55.string().nullable(),totalAmount:z55.number().nullable(),discountAmount:z55.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z55.object({id:z55.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z55.string().nullable(),currentPeriodEndsAt:z55.string().nullable(),renewsAt:z55.string().nullable(),cancelAt:z55.string().nullable(),renewAutomatically:z55.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z55.object({type:z55.enum(["low_balance","critical_balance","approaching_limit"]),message:z55.string(),estimatedPromptsRemaining:z55.number().nullable(),avgCostPerPrompt:z55.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z55.object({monthlyCredits:z55.number().nullable(),usedThisPeriod:z55.number(),remainingThisPeriod:z55.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z55.object({organizationId:z55.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z55.string().nullable(),tenureDays:z55.number().int().nonnegative(),capturedAt:z55.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z55.object({hasSubscription:z55.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z55.number().nullable(),alerts:z55.array(CreditAlertDTOSchema),portalUrl:z55.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z55.object({creditCount:z55.number().int().positive(),expiresAt:z55.string().datetime().nullable().optional(),message:z55.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z55.literal("free"),amountCents:z55.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z55.literal("purchase"),amountCents:z55.number().int().positive()}),CreditTopupRequestDTOSchema=z55.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z55.object({success:z55.boolean(),transactionId:z55.string().nullable(),newBalance:z55.number(),creditCount:z55.number(),type:z55.enum(["free","purchase"]),invoiceId:z55.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z56}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=z56.object({totalCredits:z56.number(),totalCostUsd:z56.number(),totalMessages:z56.number(),avgCostPerMessage:z56.number(),periodStart:z56.string().nullable(),periodEnd:z56.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z56.object({projectId:z56.string(),projectName:z56.string(),projectDisplayName:z56.string().nullable(),credits:z56.number(),costUsd:z56.number(),messages:z56.number(),percentage:z56.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z56.object({userId:z56.string(),userName:z56.string().nullable(),userEmail:z56.string().email().nullable(),credits:z56.number(),costUsd:z56.number(),messages:z56.number(),percentage:z56.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z56.object({date:z56.string(),credits:z56.number(),costUsd:z56.number(),messages:z56.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z56.object({userId:z56.string(),userName:z56.string().nullable(),userEmail:z56.string().email().nullable(),credits:z56.number(),costUsd:z56.number(),messages:z56.number(),percentage:z56.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z56.object({projectId:z56.string(),projectName:z56.string(),projectDisplayName:z56.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z56.array(UsageByUserForProjectDTOSchema),timeline:z56.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z56.object({summary:UsageSummaryDTOSchema,byProject:z56.array(UsageByProjectDTOSchema),byUser:z56.array(UsageByUserDTOSchema),timeline:z56.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z57}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=z57.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z57.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z57.object({startDate:z57.string().optional(),endDate:z57.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z57.coerce.number().int().positive().default(1),limit:z57.coerce.number().int().positive().max(100).default(20),sortBy:z57.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z57.string().optional()}),UsageOverviewSummaryDTOSchema=z57.object({totalCredits:z57.number(),totalCostUsd:z57.number(),totalMessages:z57.number(),avgCostPerMessage:z57.number(),avgCreditsPerMessage:z57.number(),periodStart:z57.string(),periodEnd:z57.string(),creditsChange:z57.number().nullable(),costChange:z57.number().nullable(),messagesChange:z57.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z57.object({date:z57.string(),credits:z57.number(),costUsd:z57.number(),messages:z57.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z57.object({organizationId:z57.string(),organizationName:z57.string(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number(),userCount:z57.number(),projectCount:z57.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().nullable(),userImage:z57.string().nullable(),organizationId:z57.string().nullable(),organizationName:z57.string().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number(),projectCount:z57.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),organizationId:z57.string(),organizationName:z57.string(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number(),userCount:z57.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z57.object({id:z57.string(),name:z57.string(),value:z57.number(),percentage:z57.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z57.object({day:z57.number(),hour:z57.number(),value:z57.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z57.object({summary:UsageOverviewSummaryDTOSchema,timeline:z57.array(UsageTimelinePointDTOSchema),topOrganizations:z57.array(OrganizationUsageRowDTOSchema),topUsers:z57.array(UserUsageRowDTOSchema),topProjects:z57.array(ProjectUsageRowDTOSchema),creditDistribution:z57.array(UsageDistributionItemDTOSchema),heatmap:z57.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z57.object({page:z57.number(),limit:z57.number(),totalItems:z57.number(),totalPages:z57.number(),hasMore:z57.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z57.object({organizations:z57.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z57.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z57.object({users:z57.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z57.string(),ownerName:z57.string().nullable(),ownerEmail:z57.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z57.object({projects:z57.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z57.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z57.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z57.object({credits:z57.number(),costUsd:z57.number(),messages:z57.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z57.object({id:z57.string(),name:z57.string(),createdAt:z57.string(),memberCount:z57.number(),projectCount:z57.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z57.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z57.object({id:z57.string(),name:z57.string().nullable(),email:z57.string(),image:z57.string().nullable(),createdAt:z57.string(),organizationCount:z57.number(),projectCount:z57.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z57.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z57.object({id:z57.string(),name:z57.string(),displayName:z57.string().nullable(),createdAt:z57.string(),organizationId:z57.string(),organizationName:z57.string(),ownerId:z57.string(),ownerName:z57.string().nullable(),ownerEmail:z57.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z57.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z58}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=z58.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z58.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z58.object({command:z58.string().min(1).max(1e4),cwd:z58.string().optional(),projectEnv:EnvSchema.optional(),env:z58.record(z58.string(),z58.string()).optional(),name:z58.string().optional(),waitForCompletion:z58.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z58.object({identifier:z58.string(),status:SandboxProcessStatusSchema,command:z58.string().optional(),startedAt:z58.string().optional(),exitCode:z58.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z58.object({processes:z58.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z58.object({processId:z58.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z58.object({success:z58.boolean(),message:z58.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z59}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_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit2(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit2(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit2(["status","--porcelain"],cwd)).length>0}async function cloneRepo2(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit2(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit2(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit2,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo2,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});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)}
439
439
  `)}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")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit2(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit2(["remote","add","fimo",cleanUrl],cwd)}),await runGit2(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit2(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit2(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit2(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit2(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}var init_interactive=__esm({"src/cli/utils/interactive.ts"(){init_dist();__name(isInteractive,"isInteractive");__name(assertInteractive,"assertInteractive")}});import fs17 from"node:fs";import path21 from"node:path";function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiUrl}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl};fs17.writeFileSync(path21.join(targetDir,".fimo.settings.json"),`${JSON.stringify(fimoJson,null,2)}
440
440
  `);let initialSiteName=project.displayName?.trim()||project.name,configPath=path21.join(targetDir,"fimo-config.json");if(fs17.existsSync(configPath))try{let config=JSON.parse(fs17.readFileSync(configPath,"utf-8")),seo=config.seo??{};config.seo={...seo,siteName:initialSiteName},fs17.writeFileSync(configPath,`${JSON.stringify(config,null,2)}
441
441
  `)}catch{}let envPath=path21.join(targetDir,".env"),envBlock=`VITE_API_URL=${tenantApiUrl}
@@ -1183,7 +1183,7 @@ ${failure.stderr}`});break}}__name(emitPushFailure,"emitPushFailure");function e
1183
1183
  `),padding=" ";return[JSON.stringify(first2),...rest.map(l=>`${padding}${JSON.stringify(l)}`)].join(`
1184
1184
  `)}return JSON.stringify(v)}__name(formatValue,"formatValue");function classifyStatus(diff){return diff.parent===null&&diff.child===null?"missing on both":diff.parent===null?"added on source":diff.child===null?"removed on source":diff.parent===diff.child?"unchanged":"changed"}__name(classifyStatus,"classifyStatus");function renderActivationDiff(diff,p2,opts={}){let lines=[];if(!opts.bare){lines.push(p2.bold(`${diff.agentName} \xB7 trigger ${diff.triggerIndex}`));let status=diff.parent?diff.child?"changed":"removed on source":"added on source";lines.push(p2.dim(` ${status}`)),lines.push("")}return lines.push(...fieldRow("enabled",diff.parent?.enabled,diff.child?.enabled,p2)),lines.push(...fieldRow("triggerKind",diff.parent?.triggerKind,diff.child?.triggerKind,p2)),lines.push(...fieldRow("emailRecipients",diff.parent?.emailRecipients,diff.child?.emailRecipients,p2)),lines.push(...fieldRow("qstashScheduleId",diff.parent?.qstashScheduleId,diff.child?.qstashScheduleId,p2)),lines.push(...fieldRow("triggerSpec",summarizeSpec(diff.parent),summarizeSpec(diff.child),p2)),lines.join(`
1185
1185
  `)}__name(renderActivationDiff,"renderActivationDiff");function summarizeSpec(side){if(!side)return;let keys=Object.keys(side.triggerSpec);if(keys.length===0)return"{}";let head=keys.slice(0,2).join(", "),more=keys.length>2?`, +${keys.length-2} more`:"";return`{ ${head}${more} }`}__name(summarizeSpec,"summarizeSpec");init_esm();init_cross_surface();init_surface();function renderDiff(report,p2,opts={}){let lines=[],arrow=opts.ascii?"->":"\u2192";lines.push(p2.bold(`${report.fromEnv} ${arrow} ${report.toEnv}`)),lines.push("");let surfaceOpts={ascii:opts.ascii,...opts.all?{maxItems:Number.MAX_SAFE_INTEGER}:{}};for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);delta&&(lines.push(renderSurface(delta,p2,surfaceOpts)),lines.push(""))}return!opts.surface&&report.crossSurface&&report.crossSurface.length>0&&(lines.push(renderCrossSurface(report.crossSurface,p2,{ascii:opts.ascii})),lines.push("")),lines.join(`
1186
- `).replace(/\n+$/,"")}__name(renderDiff,"renderDiff");init_git();init_project_context();init_project();async function diffCommand(a,b,options,cmd){let program2=cmd?.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),fromEnv=a??ctx.env,toEnv=b??DEFAULT_ENV;if(!b)try{toEnv=(await api.getEnv(ctx.projectId,fromEnv)).parentEnv??DEFAULT_ENV}catch{toEnv=DEFAULT_ENV}let surface=options.surface?SurfaceNameSchema.parse(options.surface):void 0;if(surface&&options.key){await runDrillIn({api,projectId:ctx.projectId,fromEnv,toEnv,surface,key:options.key});return}if(surface==="code"){if(!await isGitRepo(cwd)){ui.error({command:"diff",code:"NOT_A_GIT_REPO",message:"Not a git repository \u2014 cannot diff the code surface locally."});return}try{let patch=await runGit2(["diff",`${fromEnv}..${toEnv}`],cwd);ui.result({command:"diff",data:{from:fromEnv,to:toEnv,surface:"code",patch},render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return patch||p2.dim("(no code differences)")},"render")})}catch(err){ui.error({command:"diff",code:"GIT_DIFF_FAILED",message:`git diff failed: ${err.message}`})}return}let report=await api.getEnvDiff(ctx.projectId,fromEnv,{against:toEnv,surfaces:surface?[surface]:void 0});ui.result({command:"diff",data:report,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return renderDiff(report,p2,{surface,all:options.all,ascii:rctx.ascii})},"render")})}__name(diffCommand,"diffCommand");async function runDrillIn(args){let{api,projectId,fromEnv,toEnv,surface,key}=args;try{switch(surface){case"code":{let payload=await api.getCodeFileDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderCodeFileDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"content":{let[collection,rowId]=splitOnce(key,":");if(!collection||!rowId)return invalidKey("content","<collection>:<rowId>");let payload=await api.getContentRowDiff(projectId,fromEnv,collection,rowId,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderContentRowDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"translations":{let[locale,i18nKey]=splitOnce(key,":");if(!locale||!i18nKey)return invalidKey("translations","<locale>:<i18nKey>");let payload=await api.getTranslationRowDiff(projectId,fromEnv,locale,i18nKey,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderTranslationRowDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"activations":{let[agentName,idxStr]=splitOnce(key,":");if(!agentName||!idxStr)return invalidKey("activations","<agentName>:<triggerIndex>");let triggerIndex=Number.parseInt(idxStr,10);if(Number.isNaN(triggerIndex))return invalidKey("activations","<agentName>:<triggerIndex>");let payload=await api.getActivationDiff(projectId,fromEnv,agentName,triggerIndex,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderActivationDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"schemas":{let payload=await api.getSchemaTypeDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderSchemaTypeDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"forms":{let payload=await api.getFormSchemaDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderFormSchemaDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"assets":{let payload=await api.getAssetDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderAssetDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}}}catch(err){let message=err instanceof Error?err.message:String(err);ui.error({command:"diff",code:"DRILL_FETCH_FAILED",message:`Failed to fetch ${surface} ${key}: ${message}`})}}__name(runDrillIn,"runDrillIn");function splitOnce(s,sep2){let idx=s.indexOf(sep2);return idx<0?[s,""]:[s.slice(0,idx),s.slice(idx+1)]}__name(splitOnce,"splitOnce");function invalidKey(surface,expected){ui.error({command:"diff",code:"DRILL_INVALID_KEY",message:`--key for surface '${surface}' must be in the form '${expected}'`})}__name(invalidKey,"invalidKey");init_dist5();init_dist();init_open();init_api();init_config();init_auth_errors();init_interactive();init_project();function resolveProject(options){if(options.project)return{projectId:options.project};let settings=loadProjectSettings(resolveProjectCwd(options.cwd));return{projectId:settings.projectId,organizationId:settings.organizationId}}__name(resolveProject,"resolveProject");function derivePublicDomain(project,fallback){if(project?.appUrl)try{let parts=new URL(project.appUrl).hostname.split(".");if(parts.length>=2)return parts.slice(1).join(".")}catch{}return fallback}__name(derivePublicDomain,"derivePublicDomain");async function loadPublicDomain(api,project){if(project?.appUrl)return derivePublicDomain(project,"fimo.site");try{let features=await api.getFeatures();return derivePublicDomain(project,features.publicationDomain)}catch{return derivePublicDomain(project,"fimo.site")}}__name(loadPublicDomain,"loadPublicDomain");function paywallHint(organizationId){return`Custom domains require a Premium plan. Upgrade at ${organizationId?`https://fimo.ai/billing/${organizationId}`:"https://fimo.ai/billing"}`}__name(paywallHint,"paywallHint");function isPaywall(err){return err instanceof ApiRequestError&&err.status===403}__name(isPaywall,"isPaywall");function updateErrorToMessage(reason){switch(reason){case"invalid_shape":return"Invalid URL. Use lowercase letters, numbers, and hyphens (max 63 chars).";case"reserved":case"taken_by_project":case"taken_by_legacy_custom_domain":return"This URL is not available.";case"kv_sync_failed":return"Couldn't sync the URL. Try again in a moment.";default:return"Failed to update URL."}}__name(updateErrorToMessage,"updateErrorToMessage");function pad(value,width){return value.length>=width?value:value+" ".repeat(width-value.length)}__name(pad,"pad");function statusLabel2(domain){return domain.status==="active"&&domain.ssl.status==="active"?"verified":domain.ssl.status==="failed"||(domain.ssl.validationErrors?.length??0)>0?"failed":"pending"}__name(statusLabel2,"statusLabel");function renderDnsInstructions(domain){if(domain.dnsAutoConfigured)return"DNS auto-configured by Fimo \u2014 nothing to do.";let rows=[];rows.push({type:"CNAME",name:domain.hostname,value:domain.cnameTarget}),domain.ownershipVerification&&rows.push({type:domain.ownershipVerification.type??"TXT",name:domain.ownershipVerification.name,value:domain.ownershipVerification.value});for(let record of domain.ssl.validationRecords??[])record.txtName&&record.txtValue?rows.push({type:"TXT",name:record.txtName,value:record.txtValue}):record.cname&&record.cnameTarget&&rows.push({type:"CNAME",name:record.cname,value:record.cnameTarget});let typeW=Math.max(4,...rows.map(r=>r.type.length)),nameW=Math.max(4,...rows.map(r=>r.name.length)),lines=["","DNS records to add at your registrar:",""];lines.push(` ${pad("TYPE",typeW)} ${pad("NAME",nameW)} VALUE`);for(let r of rows)lines.push(` ${pad(r.type,typeW)} ${pad(r.name,nameW)} ${r.value}`);return lines.join(`
1186
+ `).replace(/\n+$/,"")}__name(renderDiff,"renderDiff");init_git();init_project_context();init_project();async function diffCommand(a,b,options,cmd){let program2=cmd?.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),fromEnv=a??ctx.env,toEnv=b??DEFAULT_ENV;if(!b)try{toEnv=(await api.getEnv(ctx.projectId,fromEnv)).parentEnv??DEFAULT_ENV}catch{toEnv=DEFAULT_ENV}let surface=options.surface?SurfaceNameSchema.parse(options.surface):void 0;if(surface&&options.key){await runDrillIn({api,projectId:ctx.projectId,fromEnv,toEnv,surface,key:options.key});return}if(surface==="code"){if(!await isGitRepo(cwd)){ui.error({command:"diff",code:"NOT_A_GIT_REPO",message:"Not a git repository \u2014 cannot diff the code surface locally."});return}try{let patch=await runGit2(["diff",`${fromEnv}..${toEnv}`],cwd);ui.result({command:"diff",data:{from:fromEnv,to:toEnv,surface:"code",patch},render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return patch||p2.dim("(no code differences)")},"render")})}catch(err){ui.error({command:"diff",code:"GIT_DIFF_FAILED",message:`git diff failed: ${err.message}`})}return}let report=await api.getEnvDiff(ctx.projectId,fromEnv,{against:toEnv,surfaces:surface?[surface]:void 0});ui.result({command:"diff",data:report,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return renderDiff(report,p2,{surface,all:options.all,ascii:rctx.ascii})},"render")})}__name(diffCommand,"diffCommand");async function runDrillIn(args){let{api,projectId,fromEnv,toEnv,surface,key}=args;try{switch(surface){case"code":{let payload=await api.getCodeFileDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderCodeFileDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"content":{let[collection,rowId]=splitOnce(key,":");if(!collection||!rowId)return invalidKey("content","<collection>:<rowId>");let payload=await api.getContentRowDiff(projectId,fromEnv,collection,rowId,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderContentRowDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"translations":{let[locale,i18nKey]=splitOnce(key,":");if(!locale||!i18nKey)return invalidKey("translations","<locale>:<i18nKey>");let payload=await api.getTranslationRowDiff(projectId,fromEnv,locale,i18nKey,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderTranslationRowDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"activations":{let[agentName,idxStr]=splitOnce(key,":");if(!agentName||!idxStr)return invalidKey("activations","<agentName>:<triggerIndex>");let triggerIndex=Number.parseInt(idxStr,10);if(Number.isNaN(triggerIndex))return invalidKey("activations","<agentName>:<triggerIndex>");let payload=await api.getActivationDiff(projectId,fromEnv,agentName,triggerIndex,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderActivationDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"schemas":{let payload=await api.getSchemaTypeDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderSchemaTypeDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"forms":{let payload=await api.getFormSchemaDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderFormSchemaDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"assets":{let payload=await api.getAssetDiff(projectId,fromEnv,key,{against:toEnv});ui.result({command:"diff",data:payload,render:__name(rctx=>renderAssetDiff(payload,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}}}catch(err){let message=err instanceof Error?err.message:String(err);ui.error({command:"diff",code:"DRILL_FETCH_FAILED",message:`Failed to fetch ${surface} ${key}: ${message}`})}}__name(runDrillIn,"runDrillIn");function splitOnce(s,sep2){let idx=s.indexOf(sep2);return idx<0?[s,""]:[s.slice(0,idx),s.slice(idx+1)]}__name(splitOnce,"splitOnce");function invalidKey(surface,expected){ui.error({command:"diff",code:"DRILL_INVALID_KEY",message:`--key for surface '${surface}' must be in the form '${expected}'`})}__name(invalidKey,"invalidKey");init_dist5();init_dist();init_open();init_api();init_config();init_auth_errors();init_interactive();init_project();function resolveProject(options){if(options.project)return{projectId:options.project};let settings=loadProjectSettings(resolveProjectCwd(options.cwd));return{projectId:settings.projectId,organizationId:settings.organizationId}}__name(resolveProject,"resolveProject");function derivePublicDomain(project,fallback){if(project?.appUrl)try{let parts=new URL(project.appUrl).hostname.split(".");if(parts.length>=2)return parts.slice(1).join(".")}catch{}return fallback}__name(derivePublicDomain,"derivePublicDomain");async function loadPublicDomain(api,project){if(project?.appUrl)return derivePublicDomain(project,"fimo.site");try{let features=await api.getFeatures();return derivePublicDomain(project,features.publicationDomain)}catch{return derivePublicDomain(project,"fimo.site")}}__name(loadPublicDomain,"loadPublicDomain");function paywallHint(organizationId){return`Custom domains require a Premium plan. Upgrade at ${organizationId?`https://fimo.ai/billing/${organizationId}`:"https://fimo.ai/billing"}`}__name(paywallHint,"paywallHint");function isPaywall(err){return err instanceof ApiRequestError&&err.status===403}__name(isPaywall,"isPaywall");function updateErrorToMessage(reason){switch(reason){case"invalid_shape":return"Invalid URL. Use lowercase letters, numbers, and hyphens (max 63 chars).";case"reserved":case"taken_by_project":case"taken_by_legacy_custom_domain":return"This URL is not available.";case"kv_sync_failed":return"Couldn't sync the URL. Try again in a moment.";default:return"Failed to update URL."}}__name(updateErrorToMessage,"updateErrorToMessage");function pad(value,width){return value.length>=width?value:value+" ".repeat(width-value.length)}__name(pad,"pad");function statusLabel2(domain){return domain.status==="active"&&domain.ssl.status==="active"?"verified":domain.ssl.status==="failed"||(domain.ssl.validationErrors?.length??0)>0?"failed":"pending"}__name(statusLabel2,"statusLabel");function renderDnsInstructions(domain){if(domain.dnsAutoConfigured)return"DNS auto-configured by Fimo \u2014 nothing to do.";let rows=[];rows.push({type:"CNAME",name:domain.hostname,value:domain.cnameTarget});for(let record of domain.ownershipVerification??[])rows.push({type:record.type??"TXT",name:record.name,value:record.value});for(let record of domain.ssl.validationRecords??[])record.txtName&&record.txtValue?rows.push({type:"TXT",name:record.txtName,value:record.txtValue}):record.cname&&record.cnameTarget&&rows.push({type:"CNAME",name:record.cname,value:record.cnameTarget});let typeW=Math.max(4,...rows.map(r=>r.type.length)),nameW=Math.max(4,...rows.map(r=>r.name.length)),lines=["","DNS records to add at your registrar:",""];lines.push(` ${pad("TYPE",typeW)} ${pad("NAME",nameW)} VALUE`);for(let r of rows)lines.push(` ${pad(r.type,typeW)} ${pad(r.name,nameW)} ${r.value}`);return lines.join(`
1187
1187
  `)}__name(renderDnsInstructions,"renderDnsInstructions");function parseWait(opts,defaultEnabled){if(opts.noWait)return{enabled:!1,timeoutMs:0};if(opts.wait===void 0||opts.wait===null)return{enabled:defaultEnabled,timeoutMs:300*1e3};if(opts.wait===!0)return{enabled:!0,timeoutMs:300*1e3};let match=String(opts.wait).trim().toLowerCase().match(/^(\d+)(s|m)?$/);if(!match)return{enabled:!0,timeoutMs:300*1e3};let n=parseInt(match[1],10);return{enabled:!0,timeoutMs:(match[2]??"s")==="m"?n*6e4:n*1e3}}__name(parseWait,"parseWait");async function pollUntilVerified(api,projectId,initial,timeoutMs,organizationId){let start=Date.now(),sp=spinner(`Waiting for ${initial.hostname} (SSL: ${initial.ssl.status})`),current=initial;for(;Date.now()-start<timeoutMs;){if(current.status==="active"&&current.ssl.status==="active")return sp.succeed(`Verified \u2014 ${current.hostname} is live with SSL.`),current;if(current.ssl.status==="failed"||(current.ssl.validationErrors?.length??0)>0)return sp.fail(`SSL validation failed for ${current.hostname}.`),current;await new Promise(resolve8=>setTimeout(resolve8,5e3));try{current=await api.refreshProjectDomain(projectId,initial.id),sp.update(`Waiting for ${current.hostname} (SSL: ${current.ssl.status})`)}catch(err){return rethrowCliAuthError(err,()=>sp.fail("Authentication required")),isPaywall(err)?(sp.fail(paywallHint(organizationId)),current):(sp.fail(`Refresh failed: ${err instanceof Error?err.message:String(err)}`),current)}}return sp.fail(`Timed out after ${Math.round(timeoutMs/1e3)}s waiting for ${initial.hostname}.`),current}__name(pollUntilVerified,"pollUntilVerified");async function findDomainByIdOrHostname(api,projectId,needle){let domains2=await api.listProjectDomains(projectId),lower=needle.toLowerCase();return domains2.find(d3=>d3.id===needle||d3.hostname.toLowerCase()===lower)??null}__name(findDomainByIdOrHostname,"findDomainByIdOrHostname");async function domainsListCommand(options){let cfg=loadConfig(),api=new FimoApiClient(cfg),{projectId,organizationId}=resolveProject(options),project=await api.getProject(projectId),publicDomain=await loadPublicDomain(api,project),domains2=[],domainsBlocked=!1;try{domains2=await api.listProjectDomains(projectId)}catch(err){if(rethrowCliAuthError(err),isPaywall(err))domainsBlocked=!0;else throw err}let subdomain=project.subdomain??project.name,data2={defaultUrl:{subdomain,url:`${subdomain}.${publicDomain}`},customDomains:domains2,customDomainsBlocked:domainsBlocked};ui.result({command:"domains list",data:data2,render:__name(()=>{let lines=[];if(lines.push("Default URL"),lines.push(` ${subdomain}.${publicDomain}`),lines.push(""),lines.push("Custom domains"),domainsBlocked)return lines.push(` (${paywallHint(organizationId??project.organizationId??void 0)})`),lines.join(`
1188
1188
  `);if(domains2.length===0)return lines.push(" (none)"),lines.join(`
1189
1189
  `);let hostW=Math.max(8,...domains2.map(d3=>d3.hostname.length)),statusW=Math.max(8,...domains2.map(d3=>statusLabel2(d3).length));lines.push(` ${pad("HOSTNAME",hostW)} ${pad("STATUS",statusW)} ID`);for(let d3 of domains2)lines.push(` ${pad(d3.hostname,hostW)} ${pad(statusLabel2(d3),statusW)} ${d3.id}`);return lines.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fimo",
3
- "version": "0.7.0-staging.4",
3
+ "version": "0.7.1-staging.1",
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.7.0-staging.4",
24
+ "fimo": "0.7.1-staging.1",
25
25
  "input-otp": "^1.4.2",
26
26
  "isbot": "^5",
27
27
  "lucide-react": "^0.577.0",