fimo 0.8.0-staging.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "bundled": true,
3
3
  "bundler": "esbuild",
4
- "bundledAt": "2026-07-23T09:49:39.236Z",
4
+ "bundledAt": "2026-07-23T08:29:03.159Z",
5
5
  "cliVersion": "0.8.0",
6
6
  "external": [
7
7
  "oxc-parser",
package/dist/cli/index.js CHANGED
@@ -432,7 +432,7 @@ ${end2.comment}`:end2.comment}this.doc.range[2]=end2.offset;break}default:this.e
432
432
  `)+1;for(;nl!==0;)this.onNewLine(this.offset+nl),nl=this.source.indexOf(`
433
433
  `,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(`
434
434
  `);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(`
435
- `)}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_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=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","hosting_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()}).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()}),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 OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z55.iso.datetime({offset:!0}).pipe(z55.coerce.date()),OpsRecentChatInputSchema=z55.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z55.string().trim().min(1).max(255).optional(),limit:z55.coerce.number().int().min(1).max(200).default(100),cursor:z55.string().trim().min(1).max(2e3).optional(),slim:z55.boolean().default(!0),reason:z55.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z55.object({id:z55.string(),messageId:z55.string(),env:z55.string(),versionId:z55.string().nullable(),userId:z55.string().nullable(),role:z55.string(),parts:z55.array(z55.record(z55.string(),z55.unknown())),metadata:z55.object({status:z55.string().optional(),traceUrl:z55.string().optional(),externalFileChanges:z55.array(z55.unknown()).optional()}),stats:z55.object({toolCount:z55.number().int().nonnegative(),failedToolCount:z55.number().int().nonnegative()}),createdAt:z55.iso.datetime({offset:!0}),project:z55.object({id:z55.string(),name:z55.string(),displayName:z55.string().nullable(),organizationId:z55.string().nullable()})}),OpsRecentChatResponseSchema=z55.object({target:z55.object({backendProfile:OpsBackendProfileSchema,projectEnv:z55.string().nullable()}),window:z55.object({from:z55.iso.datetime({offset:!0}),to:z55.iso.datetime({offset:!0})}),messages:z55.object({items:z55.array(OpsRecentChatMessageSchema),nextCursor:z55.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z56}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=z56.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z56.object({total:z56.number(),base:z56.number(),purchases:z56.number(),awards:z56.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z56.object({id:z56.string(),name:z56.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z56.object({type:z56.string(),brand:z56.string().nullable(),last4:z56.string().nullable(),expirationDate:z56.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z56.object({currency:z56.string(),nextPaymentAmount:z56.number().nullable(),nextPaymentAt:z56.string().nullable(),billingInterval:z56.string().nullable(),totalAmount:z56.number().nullable(),discountAmount:z56.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z56.object({id:z56.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z56.string().nullable(),currentPeriodEndsAt:z56.string().nullable(),renewsAt:z56.string().nullable(),cancelAt:z56.string().nullable(),renewAutomatically:z56.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z56.object({type:z56.enum(["low_balance","critical_balance","approaching_limit"]),message:z56.string(),estimatedPromptsRemaining:z56.number().nullable(),avgCostPerPrompt:z56.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z56.object({monthlyCredits:z56.number().nullable(),usedThisPeriod:z56.number(),remainingThisPeriod:z56.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z56.object({organizationId:z56.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z56.string().nullable(),tenureDays:z56.number().int().nonnegative(),capturedAt:z56.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z56.object({hasSubscription:z56.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z56.number().nullable(),alerts:z56.array(CreditAlertDTOSchema),portalUrl:z56.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z56.object({creditCount:z56.number().int().positive(),expiresAt:z56.string().datetime().nullable().optional(),message:z56.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("free"),amountCents:z56.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("purchase"),amountCents:z56.number().int().positive()}),CreditTopupRequestDTOSchema=z56.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z56.object({success:z56.boolean(),transactionId:z56.string().nullable(),newBalance:z56.number(),creditCount:z56.number(),type:z56.enum(["free","purchase"]),invoiceId:z56.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z57}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=z57.object({totalCredits:z57.number(),totalCostUsd:z57.number(),totalMessages:z57.number(),avgCostPerMessage:z57.number(),periodStart:z57.string().nullable(),periodEnd:z57.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z57.object({date:z57.string(),credits:z57.number(),costUsd:z57.number(),messages:z57.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z57.array(UsageByUserForProjectDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z57.object({summary:UsageSummaryDTOSchema,byProject:z57.array(UsageByProjectDTOSchema),byUser:z57.array(UsageByUserDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z58}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=z58.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z58.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z58.object({startDate:z58.string().optional(),endDate:z58.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z58.coerce.number().int().positive().default(1),limit:z58.coerce.number().int().positive().max(100).default(20),sortBy:z58.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z58.string().optional()}),UsageOverviewSummaryDTOSchema=z58.object({totalCredits:z58.number(),totalCostUsd:z58.number(),totalMessages:z58.number(),avgCostPerMessage:z58.number(),avgCreditsPerMessage:z58.number(),periodStart:z58.string(),periodEnd:z58.string(),creditsChange:z58.number().nullable(),costChange:z58.number().nullable(),messagesChange:z58.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z58.object({date:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z58.object({organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number(),projectCount:z58.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().nullable(),userImage:z58.string().nullable(),organizationId:z58.string().nullable(),organizationName:z58.string().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),projectCount:z58.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z58.object({id:z58.string(),name:z58.string(),value:z58.number(),percentage:z58.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z58.object({day:z58.number(),hour:z58.number(),value:z58.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z58.object({summary:UsageOverviewSummaryDTOSchema,timeline:z58.array(UsageTimelinePointDTOSchema),topOrganizations:z58.array(OrganizationUsageRowDTOSchema),topUsers:z58.array(UserUsageRowDTOSchema),topProjects:z58.array(ProjectUsageRowDTOSchema),creditDistribution:z58.array(UsageDistributionItemDTOSchema),heatmap:z58.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z58.object({page:z58.number(),limit:z58.number(),totalItems:z58.number(),totalPages:z58.number(),hasMore:z58.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z58.object({organizations:z58.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z58.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z58.object({users:z58.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z58.object({projects:z58.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z58.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z58.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z58.object({credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),createdAt:z58.string(),memberCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z58.object({id:z58.string(),name:z58.string().nullable(),email:z58.string(),image:z58.string().nullable(),createdAt:z58.string(),organizationCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),displayName:z58.string().nullable(),createdAt:z58.string(),organizationId:z58.string(),organizationName:z58.string(),ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z59}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=z59.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z59.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z59.object({command:z59.string().min(1).max(1e4),cwd:z59.string().optional(),projectEnv:EnvSchema.optional(),env:z59.record(z59.string(),z59.string()).optional(),name:z59.string().optional(),waitForCompletion:z59.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z59.object({identifier:z59.string(),status:SandboxProcessStatusSchema,command:z59.string().optional(),startedAt:z59.string().optional(),exitCode:z59.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z59.object({processes:z59.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z59.object({processId:z59.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z59.object({success:z59.boolean(),message:z59.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z60}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_ops_chat_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)}
435
+ `)}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","hosting_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()}).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()}),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)}
436
436
  `)}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)}
437
437
  `);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)}
438
438
  `)}catch{}let envPath=path21.join(targetDir,".env"),envBlock=`VITE_API_URL=${tenantApiUrl}
@@ -475,10 +475,10 @@ return __eta.res;
475
475
  `)}}return returnStr}function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}function replaceChar(s){return escMap[s]}function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}function escapeRegExp2(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
476
476
  `).length}function parse8(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
477
477
  `).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp2(prefix):prefix?escapeRegExp2(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp2(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp2(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}function render(template,data2,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data2,options)}function renderAsync(template,data2,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data2,options);return Promise.resolve(res)}function renderString(template,data2){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data2)}function renderStringAsync(template,data2){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data2)}function readFile2(path49){let res="";try{res=fs20.readFileSync(path49,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path49}`):err}return res}function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path24.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path24.join(views,formattedPath)}else resolvedFilePath=path24.join(path24.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path24.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}function dirIsChild(parent2,dir){let relative3=path24.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path24.isAbsolute(relative3)}var Cacher,EtaError,EtaParseError,EtaRuntimeError,EtaFileResolutionError,EtaNameResolutionError,AsyncFunction,escMap,defaultConfig2,templateLitReg,singleQuoteReg,doubleQuoteReg,Eta$1,absolutePathRegExp,Eta,init_eta_module=__esm({"../../node_modules/.pnpm/eta@3.5.0/node_modules/eta/dist/eta.module.mjs"(){Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val2){this.cache[key]=val2}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};__name(ParseErr,"ParseErr");__name(RuntimeErr,"RuntimeErr");AsyncFunction=async function(){}.constructor;__name(compile,"compile");__name(compileToString,"compileToString");__name(compileBody,"compileBody");__name(trimWS,"trimWS");escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp2,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse8,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse8,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile2,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync4}from"node:fs";import{dirname as dirname5,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname5(fileURLToPath5(import.meta.url)),IS_BUNDLED=existsSync4(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync4}from"node:fs";import{dirname as dirname6,join as join7,resolve as resolve4}from"node:path";function getFormFiles(formsDir){return existsSync5(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join7(formsDir,f)):[]}function readForm(path49){try{return JSON.parse(readFileSync5(path49,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
478
- `)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync5(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join7(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname6(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync4(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync4(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}if(allForms.length>0){let indexPath=join7(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync5(indexPath)||readFileSync5(indexPath,"utf-8")!==indexContent)&&(writeFileSync4(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync5(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join7(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(syncForms,"syncForms")}});import{existsSync as existsSync6,mkdirSync as mkdirSync4,readFileSync as readFileSync6,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync5}from"node:fs";import{basename as basename2,dirname as dirname7,join as join8,resolve as resolve5}from"node:path";import{z as z61}from"zod";function getSchemaFiles(schemasDir){return existsSync6(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).map(f=>join8(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync6(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join8(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function resolveProjectRuntime(cwd){let packagePath=join8(cwd,"node_modules","fimo","package.json");if(!existsSync6(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let version;try{version=JSON.parse(readFileSync6(packagePath,"utf-8")).version}catch{version=null}if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname7(packagePath),version}}function templatePath(runtime,fileName){return runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)?join8(runtime.packageRoot,"assets","content-templates",fileName):assetPath("content-templates",fileName)}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename2(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename2(path49)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync6(path49,"utf-8"))}catch(error){errors.push(`${basename2(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename2(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename2(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename2(path49)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename2(path49)} has an invalid schema shape: ${details}`);continue}schemas3.push({pascal,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
478
+ `)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync5(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join7(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname6(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync4(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync4(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}if(allForms.length>0){let indexPath=join7(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync5(indexPath)||readFileSync5(indexPath,"utf-8")!==indexContent)&&(writeFileSync4(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync5(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join7(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(syncForms,"syncForms")}});import{existsSync as existsSync6,mkdirSync as mkdirSync4,readFileSync as readFileSync6,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync5}from"node:fs";import{basename as basename2,dirname as dirname7,join as join8,resolve as resolve5}from"node:path";import{z as z60}from"zod";function getSchemaFiles(schemasDir){return existsSync6(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).map(f=>join8(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync6(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join8(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function resolveProjectRuntime(cwd){let packagePath=join8(cwd,"node_modules","fimo","package.json");if(!existsSync6(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let version;try{version=JSON.parse(readFileSync6(packagePath,"utf-8")).version}catch{version=null}if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname7(packagePath),version}}function templatePath(runtime,fileName){return runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)?join8(runtime.packageRoot,"assets","content-templates",fileName):assetPath("content-templates",fileName)}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename2(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename2(path49)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync6(path49,"utf-8"))}catch(error){errors.push(`${basename2(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename2(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename2(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename2(path49)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename2(path49)} has an invalid schema shape: ${details}`);continue}schemas3.push({pascal,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
479
479
  - ${errors.join(`
480
480
  - `)}
481
- No generated files were changed.`);return schemas3}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,templates=[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta")},{suffix:".ts",path:templatePath(runtime,"hooks-template.eta")}].map(template=>({...template,source:readFileSync6(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of templates){let tsPath=join8(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model}))}}for(let[tsPath,content2]of generatedFiles){let dir=dirname7(tsPath);if(existsSync6(dir)||mkdirSync4(dir,{recursive:!0}),!existsSync6(tsPath)){writeFileSync5(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync6(tsPath,"utf-8")!==content2&&(writeFileSync5(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z61.object({uid:z61.string().min(1),isSingleton:z61.boolean().optional(),i18n:z61.object({enabled:z61.boolean().optional()}).optional(),fields:z61.record(z61.string(),z61.unknown()).optional()});__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(templatePath,"templatePath");__name(loadSchemas,"loadSchemas");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
481
+ No generated files were changed.`);return schemas3}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve5(cwd,SCHEMAS_REL),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,templates=[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta")},{suffix:".ts",path:templatePath(runtime,"hooks-template.eta")}].map(template=>({...template,source:readFileSync6(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of templates){let tsPath=join8(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model}))}}for(let[tsPath,content2]of generatedFiles){let dir=dirname7(tsPath);if(existsSync6(dir)||mkdirSync4(dir,{recursive:!0}),!existsSync6(tsPath)){writeFileSync5(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync6(tsPath,"utf-8")!==content2&&(writeFileSync5(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z60.object({uid:z60.string().min(1),isSingleton:z60.boolean().optional(),i18n:z60.object({enabled:z60.boolean().optional()}).optional(),fields:z60.record(z60.string(),z60.unknown()).optional()});__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(templatePath,"templatePath");__name(loadSchemas,"loadSchemas");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
482
482
  `)}var init_cross_surface=__esm({"src/cli/utils/format/cross-surface.ts"(){__name(renderCrossSurface,"renderCrossSurface")}});function getTerminalWidth(){let w3=process.stdout.columns;return typeof w3=="number"&&w3>0?w3:100}function layoutKeyDetail(args){let{indent,key,keyLength,detail,detailLength=0,width}=args;if(!detail)return`${indent}${key}`;let minGap=args.minGap??2,used=indent.length+keyLength+minGap+detailLength;if(width<80||used>=width)return`${indent}${key}${" ".repeat(minGap)}${detail}`;let padding=width-indent.length-keyLength-detailLength;return`${indent}${key}${" ".repeat(padding)}${detail}`}var init_columns=__esm({"src/cli/utils/format/columns.ts"(){__name(getTerminalWidth,"getTerminalWidth");__name(layoutKeyDetail,"layoutKeyDetail")}});var activations,init_activations=__esm({"src/cli/utils/format/surface-presenters/activations.ts"(){activations={label:"AGENTS",hint:"declared \xB7 active",emptyCopy:" (no agents activated)",groupBy:__name(item=>item.detail??"(no agent)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?`trigger ${item.key.slice(idx+1)}`:item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});function shortId(id){return id.length>12?`${id.slice(0,8)}\u2026`:id}var assets,init_assets2=__esm({"src/cli/utils/format/surface-presenters/assets.ts"(){assets={label:"ASSETS",hint:"media library",emptyCopy:" (no asset changes)",keyFormatter:__name(item=>item.detail??item.key,"keyFormatter"),detailFormatter:__name(item=>{if(item.detail&&item.key!==item.detail)return shortId(item.key)},"detailFormatter")};__name(shortId,"shortId")}});var code,init_code=__esm({"src/cli/utils/format/surface-presenters/code.ts"(){code={label:"CODE",hint:"git workspace vs HEAD",emptyCopy:" (clean)"}}});var content,init_content=__esm({"src/cli/utils/format/surface-presenters/content.ts"(){content={label:"CONTENT",hint:"entries per collection",emptyCopy:" (no content changes)",groupBy:__name(item=>item.detail??"(unknown)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var forms,init_forms=__esm({"src/cli/utils/format/surface-presenters/forms.ts"(){forms={label:"FORMS",hint:"schema changes",emptyCopy:" (no form changes)"}}});var schemas,init_schemas=__esm({"src/cli/utils/format/surface-presenters/schemas.ts"(){schemas={label:"SCHEMAS",hint:"content types",emptyCopy:" (no schema changes)",groupBy:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(0,idx):""},"groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter")}}});var translations,init_translations=__esm({"src/cli/utils/format/surface-presenters/translations.ts"(){translations={label:"TRANSLATIONS",hint:"per locale",emptyCopy:" (no translation changes)",groupBy:__name(item=>item.detail??"(no locale)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var SURFACE_PRESENTERS,init_surface_presenters=__esm({"src/cli/utils/format/surface-presenters/index.ts"(){init_activations();init_assets2();init_code();init_content();init_forms();init_schemas();init_translations();SURFACE_PRESENTERS={code,schemas,content,translations,assets,forms,activations}}});function renderItem(item,p2,opts={}){let glyph=VERB_GLYPHS[item.verb]??"?",colored=item.verb==="added"?p2.green(glyph):item.verb==="removed"?p2.red(glyph):item.verb==="conflict"?p2.yellow(glyph):p2.blue(glyph),indent=opts.indent??" ",displayKey=opts.presenter?.keyFormatter?opts.presenter.keyFormatter(item):item.key,displayDetail=opts.presenter?.detailFormatter?opts.presenter.detailFormatter(item):item.detail,width=opts.width;if(item.origin===void 0)return layoutCore({indent,marker:"",markerLen:0,colored,displayKey,displayDetail,width,p:p2});let marker=item.origin==="local-uncommitted"?p2.yellow("*"):" ";return layoutCore({indent,marker,markerLen:1,colored,displayKey,displayDetail,width,p:p2})}function layoutCore(args){let{indent,marker,markerLen,colored,displayKey,displayDetail,width,p:p2}=args,prefix=`${marker}${colored} ${displayKey}`,prefixLen=markerLen+1+1+displayKey.length;return displayDetail?width===void 0?`${indent}${prefix}${p2.dim(` ${displayDetail}`)}`:layoutKeyDetail({indent,key:prefix,keyLength:prefixLen,detail:p2.dim(displayDetail),detailLength:displayDetail.length,width}):`${indent}${prefix}`}function renderSurface(delta,p2,opts={}){let display=SURFACE_DISPLAY[delta.surface],presenter=SURFACE_PRESENTERS[delta.surface],lines=[],includeHeader=opts.includeHeader??!0,maxItems=opts.maxItems??50,width=opts.width??getTerminalWidth();if(includeHeader&&(lines.push(p2.bold(display.label)),lines.push(p2.dim(` ${display.hint}`))),delta.status==="timed_out")return lines.push(p2.yellow(" (surface check timed out)")),lines.join(`
483
483
  `);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
484
484
  `);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fimo",
3
- "version": "0.8.0-staging.3",
3
+ "version": "0.8.0",
4
4
  "description": "Fimo CLI - create, deploy, and manage Fimo projects",
5
5
  "bin": {
6
6
  "fimo": "dist/cli/index.js"
package/release.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "source": "npm",
3
- "apiUrl": "https://api.staging.fimo.team",
4
- "webUrl": "https://staging.fimo.team"
3
+ "apiUrl": "https://api.fimo.ai",
4
+ "webUrl": "https://fimo.ai"
5
5
  }
@@ -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.8.0-staging.3",
24
+ "fimo": "0.8.0",
25
25
  "input-otp": "^1.4.2",
26
26
  "isbot": "^5",
27
27
  "lucide-react": "^0.577.0",